package com.hotel.BL;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.EntityName;
import com.StatusTitle;
import com.Util;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.SortDirection;

import data.Agency;
import data.Charge;
import data.DNR;
import data.Folio;
import data.Group;
import data.PackageByDate;
import data.PayType;
import data.Payment;
import data.ReasonDetail;
import data.Reservation;
import data.ReservationStatus;
import data.Room;
import data.Guest;
import data.SourcesBusiness;
import data.SubPayment;
import data.SubReservation;
import data.passingData.NightAuditReportResData;
import data.passingData.PaymentData;
import data.passingData.ReservationData;
import data.passingData.ReservationDataForReport;
import data.passingData.ReservationDataFullWithTask;

public class ReservationLogic extends AbstractBL {
	
	public ReservationLogic(HttpServletRequest req, HttpServletResponse resp)
	{
		this.req = req;
		this.resp = resp;
	}
	
	public List<ReservationData> GetReservationListWithoutCancel(long hotelId, Date from,
			long span) throws ParseException {

		List<ReservationData> list = new ArrayList<ReservationData>();
		ReservationStatus cancelStatus = new GenericLogic(req,resp).GetReservationStatus(hotelId,StatusTitle.ReservationStatus.CancelReservation);
		String cancelId = cancelStatus.getId()+"";
		List<Reservation> resvList = GetReservation(hotelId, from, span);
		for (Reservation r : resvList) {
			if(r.getReservationStatusString().trim().equals(cancelId))
				continue;
			ReservationData res = new ReservationData();
			res.setId(r.getId());
			if(r.getGuestString()==null||r.getGuestString().equals("0")){
				res.setName("");
			}else{
				res.setName(r.getGuest().getFirstName() + " "
						+ r.getGuest().getLastName());
			}
			res.setAssign(r.isAssign());
			res.setGroupId(r.getGroupIdNumber());
			if(r.getGroupIdString()!=null && !r.getGroupIdString().equals("0")){	
				if(r.getGroupId().getGuest()!=null){	
			res.setGroupName(r.getGroupId().getGuest().getFirstName()+" "+r.getGroupId().getGuest().getLastName());
				}
			}
			res.setRoomNameId(r.getRoom().getId());
			res.setRoomTypeId(r.getRoom().getRoomtype().getId());
			
			res.setRealDate(r.getDate());
			res.setDate(r.getDate());
			
			Date to = Util.addDays(from, span);
			Date r_fromDate = r.getDate();
			Date r_toDate = r.getDateTo();
			
			if(r_fromDate.before(from))
			{
				res.setDate(from);
			}
			if(r_toDate.after(to))
				res.setSpan(Util.daysBetween(res.getDate(), to));
			else
				res.setSpan(Util.daysBetween(res.getDate(), r_toDate));
			
			if(res.getSpan() == 0)
				continue;
			
			res.setRealSpan(r.getSpan());
			res.setOrder(r.getOrder());

			res.setResStatus(r.getReservationStatusString());
			res.setSellRoom(r.getSellRoom());
			//add subreservation
			List<SubReservation> subList= r.getSubReservationList();
			Date maxDate = Util.addDays(from,span);
			for(SubReservation sub:subList)
			{
				Date fromDate = sub.getDate();
				Date toDate = Util.addDays(fromDate,sub.getSpan());
				
				if(fromDate.after(maxDate) || !toDate.after(from))
					continue;
				
				ReservationData newRes = res.clone();
				newRes.setSubId(sub.getId());
				newRes.setSpan(sub.getSpan());
				newRes.setDate(fromDate);
				newRes.setDateTo(toDate);
				
				if(!fromDate.equals(r.getDate()) && !fromDate.before(from))
					newRes.setChangeRoomFrom(true);
				if(!toDate.equals(r.getDateTo()) && !toDate.after(maxDate))
					newRes.setChangeRoomTo(true);
				
				if(toDate.after(maxDate))
				{
					newRes.setSpan(sub.getSpan() - Util.daysBetween(maxDate, toDate));
					newRes.setDateTo(Util.addDays(maxDate,-1));
				}

				newRes.setRoomNameId(sub.getRoom().getId());
				newRes.setRoomTypeId(sub.getRoom().getRoomtype().getId());

				newRes.setRealDate(fromDate);
				if(newRes.getDate().before(from))
				{
			        long newspan = (newRes.getSpan() - Util.daysBetween(newRes.getDate(), from));
					newRes.setDate(from);
			        newRes.setSpan(newspan);
				}
				list.add(newRes);
			}
			
			if(subList.size() == 0)
				list.add(res);
		}

		return list;
	}
	
	public List<ReservationData> GetReservationList(long hotelId, Date from,
			long span) throws ParseException {

		List<ReservationData> list = new ArrayList<ReservationData>();

		List<Reservation> resvList = GetReservation(hotelId, from, span);
		for (Reservation r : resvList) {

			ReservationData res = new ReservationData();
			res.setId(r.getId());
			if(r.getGuestString()==null||r.getGuestString().equals("0")){
				res.setName("");
			}else{
				res.setName(r.getGuest().getFirstName() + " "
						+ r.getGuest().getLastName());
			}
			res.setAssign(r.isAssign());
			res.setGroupId(r.getGroupIdNumber());
			if(r.getGroupIdString()!=null && !r.getGroupIdString().equals("0")){	
				if(r.getGroupId().getGuest()!=null){	
			res.setGroupName(r.getGroupId().getGuest().getFirstName()+" "+r.getGroupId().getGuest().getLastName());
				}
			}
			res.setRoomNameId(r.getRoom().getId());
			res.setRoomTypeId(r.getRoom().getRoomtype().getId());
			
			res.setRealDate(r.getDate());
			res.setDate(r.getDate());
			
			Date to = Util.addDays(from, span);
			Date r_fromDate = r.getDate();
			Date r_toDate = r.getDateTo();
			
			if(r_fromDate.before(from))
			{
				res.setDate(from);
			}
			if(r_toDate.after(to))
				res.setSpan(Util.daysBetween(res.getDate(), to));
			else
				res.setSpan(Util.daysBetween(res.getDate(), r_toDate));
			
			if(res.getSpan() == 0)
				continue;
			
			res.setRealSpan(r.getSpan());
			res.setOrder(r.getOrder());

			res.setResStatus(r.getReservationStatusString());
			res.setSellRoom(r.getSellRoom());
			//add subreservation
			List<SubReservation> subList= r.getSubReservationList();
			Date maxDate = Util.addDays(from,span);
			for(SubReservation sub:subList)
			{
				Date fromDate = sub.getDate();
				Date toDate = Util.addDays(fromDate,sub.getSpan());
				
				if(fromDate.after(maxDate) || !toDate.after(from))
					continue;
				
				ReservationData newRes = res.clone();
				newRes.setSubId(sub.getId());
				newRes.setSpan(sub.getSpan());
				newRes.setDate(fromDate);
				newRes.setDateTo(toDate);
				
				if(!fromDate.equals(r.getDate()) && !fromDate.before(from))
					newRes.setChangeRoomFrom(true);
				if(!toDate.equals(r.getDateTo()) && !toDate.after(maxDate))
					newRes.setChangeRoomTo(true);
				
				if(toDate.after(maxDate))
				{
					newRes.setSpan(sub.getSpan() - Util.daysBetween(maxDate, toDate));
					newRes.setDateTo(Util.addDays(maxDate,-1));
				}

				newRes.setRoomNameId(sub.getRoom().getId());
				newRes.setRoomTypeId(sub.getRoom().getRoomtype().getId());

				newRes.setRealDate(fromDate);
				if(newRes.getDate().before(from))
				{
			        long newspan = (sub.getSpan() - Util.daysBetween(newRes.getDate(), from));
					newRes.setDate(from);
			        newRes.setSpan(newspan);
				}
				list.add(newRes);
			}
			
			if(subList.size() == 0)
				list.add(res);
		}

		return list;
	}
	
	public ReservationData TrimReservationToSpanDate(ReservationData r,Date from,long span){
		ReservationData resData = r.clone();
		resData.setRealDate(r.getDate());
		resData.setRealSpan(r.getSpan());
		
		if(resData.getDate().before(from))
		{
			resData.setSpan(resData.getSpan() - Util.daysBetween(resData.getDate(), from));
			resData.setDate(from);
		}
		if(Util.addDays(resData.getDate(),resData.getSpan()).after(Util.addDays(from,span)))
		{
			resData.setSpan(Util.daysBetween(resData.getDate(),Util.addDays(from,span)));
			resData.setDateTo(Util.addDays(from,span));
		}
		return resData;
	}

	public List<ReservationData> GetReservationAll(long hotelId)
			throws ParseException {

		List<ReservationData> list = new ArrayList<ReservationData>();

		List<Reservation> resvList = GetReservation_All(hotelId);
		for (Reservation r : resvList) {

			ReservationData res = new ReservationData();
			res.setId(r.getId());
			res.setName(r.getGuest().getFirstName() + " "
					+ r.getGuest().getLastName());
			res.setAssign(r.isAssign());
			res.setGroupId(r.getGroupIdNumber());
			res.setRoomNameId(r.getRoom().getId());
			res.setRoomTypeId(r.getRoom().getRoomtype().getId());
			res.setDate(r.getDate());
			res.setOrder(r.getOrder());

			res.setColor(r.getReservationStatus().getColor());
			res.setReservationTitle(r.getReservationStatus().getTitle());
			res.setSellRoom(r.getSellRoom());
			list.add(res);
		}
		return list;
	}
	///// Check Out 
	public List<ReservationDataForReport> GetReservationAllReportCheckoutOnlyPage(long hotelId,String TypePage,String dateCheckin ,
			String dateCheckout,long line,long pointer,String SearchAll_checkoutPage)
			throws ParseException {
 		Double sumAmount = 0.0;
		Double sumAmountPayment = 0.0;
		Double sumAmountPaymentGroup = 0.0;
		Double sumAmountCharge = 0.0;
		int checkSizeSubList = 0;
		int checkGroupSubList = 0;
		List<ReservationDataForReport> list = new ArrayList<ReservationDataForReport>();
		List<Reservation> resvList;
		resvList = GetReservation_AllCheckoutOnlyPage(hotelId,TypePage,dateCheckin,dateCheckout,line,pointer);
		Date nowDate1 = new GenericLogic(req,resp).ServerDateTime(hotelId);
		TaxLogic taxLogic = new TaxLogic(req,resp);
		FolioLogic folioLogic = new FolioLogic(req,resp);
		ChargeLogic chargeLogic = new ChargeLogic(req,resp);
		SubPaymentLogic subPaymentLogic = new SubPaymentLogic(req,resp);
		SimpleDateFormat nowDate = new SimpleDateFormat("yyyyMMdd");
		String CheckGroup = "";
		Double checkBalance = 0.0;
		for (Reservation r : resvList) {
				String checkFilter = "";
				if(list.size() < (line*pointer)){
					List<ReservationDataForReport> sublist = new ArrayList<ReservationDataForReport>();
					ReservationDataForReport res = new ReservationDataForReport();
				if(r.getGroupIdNumber()!=0){
					checkGroupSubList = 0;
					Double checkChargeFolioGroup = 0.0;
					Double checkPaidFolioGroup = 0.0;
					String FolioStringDataGroup = "";
					if(r.getFolioListString()!=null){
					    	String[] ListArrayFolio = r.getFolioListString().split(",");
						    if(!ListArrayFolio.equals("")){
						    	for(int i = 0;i<ListArrayFolio.length;i++){
						    		long folioId = Long.parseLong(ListArrayFolio[i]);
						    		Folio foliodata = folioLogic.GetFolio(folioId);
						    		if(foliodata.isLock()==true){
						    			FolioStringDataGroup = "INV "+String.valueOf(foliodata.getId());
						    		}else{
						    			FolioStringDataGroup = "IP "+String.valueOf(foliodata.getId());
						    			for(int c = 0;c<foliodata.getCharge().size();c++){
						    				checkChargeFolioGroup += foliodata.getCharge().get(c).getChargeAmount();
						    				checkChargeFolioGroup += foliodata.getCharge().get(c).getTax();
						    			}
						    			if(foliodata.getPaymentString()!=null)
							    			if(!foliodata.getPaymentString().equals("")){
							    				String [] subPaymentFolio = foliodata.getPaymentString().split(",");
							    				for(int p =0;p<subPaymentFolio.length;p++){
							    					Long subpaymentId = Long.parseLong(subPaymentFolio[p]);
							    					SubPayment sp =  subPaymentLogic.GetSubPayment(subpaymentId);
							    					checkPaidFolioGroup += sp.getAmount();
							    				}
							    			}
						    		}
						    	}
						    	res.setChargeFolio(checkChargeFolioGroup);
						    	res.setPaidFolio(checkPaidFolioGroup);
						    	res.setBalance(checkChargeFolioGroup-checkPaidFolioGroup);
						    	//Double checkBalance = checkChargeFolioGroup-checkPaidFolioGroup;
						    	/*if(checkBalance==0){
						    		continue;
						    	}*/
						    }
						    res.setFolioId(FolioStringDataGroup);
						    FolioStringDataGroup="";
					}
					 	res.setTypePage(TypePage);
						if(!CheckGroup.equals(r.getGroupIdString())){
						res.setResLis(r.getGroupId().getListResvString());
						String[] splitResId = r.getGroupId().getListResvString().split(",");
						for(int i =0;i<splitResId.length;i++){
							if(SearchAll_checkoutPage!=null)
								if(SearchAll_checkoutPage.equals(splitResId[i]))
									checkFilter = "true";
						}
						res.setGroupIdString(r.getGroupIdString());
						res.setGroupId(r.getGroupIdNumber());
						res.setId(r.getId());
						r.getGroupId().getPaymentListString().split(",");
						// set Folio status INV,IP INV balance = 0;
					    String FolioStringData = "";
					    if(r.getGroupId().getFolioListString()!=null){
					    	String[] ListArrayFolio = r.getGroupId().getFolioListString().split(",");
						    if(!ListArrayFolio.equals("")){
						    	for(int i = 0;i<ListArrayFolio.length;i++){
						    		long folioId = Long.parseLong(ListArrayFolio[i]);
						    		Folio foliodata = folioLogic.GetFolio(folioId);
						    		if(foliodata.isLock()==true){
						    			FolioStringData = "INV "+String.valueOf(foliodata.getId());
						    		}else{
						    			FolioStringData = "IP "+String.valueOf(foliodata.getId());
						    		}
						    	}
						    }
					    }
					    res.setFolioId(FolioStringData);
					    FolioStringData = "";
						// payment
					    PaymentLogic paymentLogic = new PaymentLogic(req,resp);
						String[] ListArrayPaymentListGroup = r.getGroupId().getPaymentListString().split(",");
						for(int j = 0;j<ListArrayPaymentListGroup.length;j++){
							String paymentIdStringGroup = String.valueOf(ListArrayPaymentListGroup[j]);
							if(!paymentIdStringGroup.equals("")){
								Payment P = paymentLogic.GetPayment(Long.parseLong(paymentIdStringGroup));
								sumAmountPaymentGroup += P.getAmount();
							}
						}
						res.setPaymentAmount(sumAmountPaymentGroup);
						sumAmountPaymentGroup = 0.0;
						// set customer
						if(r.getGroupId().getGuest()!=null){
							String name = r.getGroupId().getGuest().getFirstName();
							String groupId =String.valueOf(r.getGroupId().getId());
							if(SearchAll_checkoutPage!=null&&!SearchAll_checkoutPage.equals("")){
								String firstStringSearch = SearchAll_checkoutPage.substring(0,1);
								if(firstStringSearch.equals("G")||firstStringSearch.equals("g"))
									SearchAll_checkoutPage = SearchAll_checkoutPage.substring(1,SearchAll_checkoutPage.length());
								if(SearchAll_checkoutPage.equals(name)){
									checkFilter = "true";
								}
								if(SearchAll_checkoutPage.equals(groupId)){
									checkFilter = "true";
								}
								if(!checkFilter.equals("true"))
									continue;
							}
							res.setName(r.getGroupId().getGuest().getFirstName() +" "+r.getGroupId().getGuest().getLastName());
							res.setGuestId(r.getGroupId().getGuest().getId());
							res.setPhone(r.getGroupId().getGuest().getPhone());
						}else{
							res.setName("");
						}
						// set room
						res.setPhone(r.getGroupId().getGuest().getPhone());
						res.setDescription(r.getGroupId().getNote());
						res.setAssign(r.isAssign());
						res.setRoomName(r.getRoom().getRoomName());
						res.setRoomTypeName(r.getRoom().getRoomtype().getShortName());
						res.setRoomNameId(r.getRoom().getId());
						res.setRoomTypeId(r.getRoom().getRoomtype().getId());
						// set date
						res.setDate(r.getDate());
						res.setDateTo(r.getDateTo());
						res.setOrder(r.getOrder());
						res.setColor(r.getReservationStatus().getColor());
						res.setReservationTitle(r.getReservationStatus().getTitle());
						res.setSellRoom(r.getSellRoom());
						res.setSpan(r.getGroupId().getSpan());
						// set reservation in group
						String[] ArrayResvList = r.getGroupId().getListResvString().split(",");
						for(int i = 0;i<ArrayResvList.length;i++){
							ReservationDataForReport Subres = new ReservationDataForReport();
							Reservation rsv = GetReservation(Long.parseLong(ArrayResvList[i].trim()));
							Double checkChargeFolioSubRes = 0.0;
							Double checkPaidFolioSubRes = 0.0;
							String FolioStringDataSubRes = "";
								if(r.getFolioListString()!=null){
						    	String[] ListArrayFolio = rsv.getFolioListString().split(",");
						    	if(!ListArrayFolio.equals("")){
							    	for(int f = 0;f<ListArrayFolio.length;f++){
							    		long folioId = Long.parseLong(ListArrayFolio[f]);
							    		Folio foliodata = folioLogic.GetFolio(folioId);
							    		if(foliodata.isLock()==true){
							    			FolioStringDataSubRes = "INV "+String.valueOf(foliodata.getId());
							    		}else{
							    			FolioStringDataSubRes = "IP "+String.valueOf(foliodata.getId());
							    			for(int c = 0;c<foliodata.getCharge().size();c++){
							    				checkChargeFolioSubRes += foliodata.getCharge().get(c).getChargeAmount();
							    			}
							    			if(foliodata.getPaymentString()!=null)
								    			if(!foliodata.getPaymentString().equals("")){
								    				String [] subPaymentFolio = foliodata.getPaymentString().split(",");
								    				for(int p =0;p<subPaymentFolio.length;p++){
								    					long subpaymentId = Long.parseLong(subPaymentFolio[p]);
								    					SubPayment sp =  subPaymentLogic.GetSubPayment(subpaymentId);
								    					checkPaidFolioSubRes += sp.getAmount();
								    				}
								    			}
							    		}
							    		FolioStringDataGroup += FolioStringDataSubRes+",<br>";
							    	}
							    	checkChargeFolioGroup += checkChargeFolioSubRes;
							    	checkPaidFolioGroup   += checkPaidFolioSubRes;
							    	Subres.setChargeFolio(checkChargeFolioSubRes);
							    	Subres.setPaidFolio(checkPaidFolioSubRes);
							    	Subres.setBalance(checkChargeFolioSubRes-checkPaidFolioSubRes);
							    	checkBalance = checkChargeFolioSubRes-checkPaidFolioSubRes;
							    }
							    Subres.setFolioId(FolioStringDataSubRes);
							    FolioStringDataSubRes="";
						    }
							Subres.setGroupId(rsv.getGroupIdNumber());
							Subres.setId(rsv.getId());
							String[] ListArrayCharge = rsv.getChargeListString().split(",");
							
							String[] ListArrayPaymentList = rsv.getPaymentListString().split(",");
						    String chargeAmount;
						    String chargeAmountTemp;
						    // set Folio status INV,IP INV balance = 0;
						    String FolioStringData_ResIngroup = "";
						    if(rsv.getFolioListString()!=null){
						    	String[] ListArrayFolio = rsv.getFolioListString().split(",");
							    if(!ListArrayFolio.equals("")){
							    	for(int f = 0;f<ListArrayFolio.length;f++){
							    		long folioId = Long.parseLong(ListArrayFolio[f]);
							    		Folio foliodata = folioLogic.GetFolio(folioId);
							    		if(foliodata.isLock()==true){
							    			FolioStringData_ResIngroup = "INV "+String.valueOf(foliodata.getId());
							    		}else{
							    			FolioStringData_ResIngroup = "IP "+String.valueOf(foliodata.getId());
							    		}
							    	}
							    }
						    }
						    Subres.setFolioId(FolioStringData_ResIngroup);
						    FolioStringData_ResIngroup="";
							// set charge
							for(int j = 0;j<ListArrayCharge.length;j++){
								Charge Ct = chargeLogic.GetCharge(Long.parseLong(ListArrayCharge[j]));
								if(Ct.isTemp()==false)
									sumAmountCharge += (Ct.getChargeAmount()+Ct.getTax());
								sumAmount += Ct.getChargeAmount();
							}
							if(rsv.getOtherChargeString()!=null&&!rsv.getOtherChargeString().equals("")){
								for(int k = 0;k<rsv.getOtherChargeList().size();k++){
									Charge OCt = rsv.getOtherChargeList().get(k);
									sumAmountCharge += (OCt.getChargeAmount()+OCt.getTax());
								}
							}
							chargeAmountTemp = String.valueOf(sumAmountCharge);
							chargeAmount = String.valueOf(sumAmount+(taxLogic.CalTax(hotelId,sumAmount)));
							Subres.setChargeCheckTemp(chargeAmountTemp);
							Subres.setDefaultCherge(sumAmount);
							Subres.setTax(taxLogic.CalTax(hotelId,sumAmount));
							Subres.setTotaltax(sumAmount+(taxLogic.CalTax(hotelId,sumAmount)));
							sumAmountCharge = 0.0;
							// set payment
							if(!ListArrayPaymentList[0].equals("")){
								for(int j = 0;j<ListArrayPaymentList.length;j++){
									String paymentIdString = String.valueOf(ListArrayPaymentList[j]);
									if(!paymentIdString.equals("")){
										Payment P = paymentLogic.GetPayment(Long.parseLong(paymentIdString));
										sumAmountPayment += P.getAmount();
									}
								}
							}
							Subres.setPaymentAmount(sumAmountPayment);
							Subres.setPaymentList(chargeAmount);
							Subres.setPracketPrice(rsv.getPackageByDate().get(0).getPackages().getName());
							sumAmount = 0.0;
							sumAmountPayment = 0.0;
							// set customer
							if(rsv.getSourcesString()!=null){
								SourcesBusiness S = new SourcesBusinessLogic().GetSourcesBusiness(Long.parseLong(rsv.getSourcesString()));
								Subres.setSourcesString(S.getTitle());
							}
							// set customer
							if(!rsv.getGuestString().equals("0")){
								Subres.setName(rsv.getGuest().getFirstName() +" "+ rsv.getGuest().getLastName());
								Subres.setGuestId(rsv.getGuest().getId());
								Subres.setPhone(rsv.getGuest().getPhone());
							}
							// set room
							Subres.setAssign(rsv.isAssign());
							Subres.setRoomName(rsv.getRoom().getRoomName());
							Subres.setRoomTypeName(rsv.getRoom().getRoomtype().getShortName());
							Subres.setRoomNameId(rsv.getRoom().getId());
							Subres.setRoomTypeId(rsv.getRoom().getRoomtype().getId());
							Subres.setAdult(rsv.getAdult());
							Subres.setChild(rsv.getChild());
							Subres.setDescription(rsv.getNote());
							Subres.setSellRoom(rsv.getSellRoom());
							Subres.setSpan(rsv.getSpan());
							// set date
							Subres.setDate(rsv.getDate());
							Subres.setDateTo(rsv.getDateTo());
							Subres.setOrder(rsv.getOrder());
							Subres.setColor(rsv.getReservationStatus().getColor());
							Subres.setReservationTitle(rsv.getReservationStatus().getTitle());
							if(((line*pointer)-checkSizeSubList)>0){
							//	pointer
								sublist.add(Subres);
								checkGroupSubList = 1;
								checkSizeSubList++;
							}
						}
						res.setSubList(sublist);
						if(dateCheckout!=null&&!dateCheckout.equals("")){
							if(TypePage=="ExpressGroup"){
								if(!r.getGroupIdString().equals("0")||!r.getGroupIdString().equals("")){
									if(checkGroupSubList==0)
										continue;
									if(checkBalance==0)
						    			continue;
									list.add(res);
								}else
									checkSizeSubList=0;
							}else if(TypePage=="CheckOutOnlyGroup"||TypePage=="CheckOutPendingGroup"){
								if(!r.getGroupIdString().equals("0")||!r.getGroupIdString().equals("")){
									if(checkGroupSubList==0)
										continue;
									list.add(res);
								}else
									checkSizeSubList=0;
							}else if(TypePage=="ExpressSingle"){
								if(r.getGroupIdString().equals("0")||r.getGroupIdString().equals("")){
									if(((line*pointer)-checkSizeSubList)>0){
										if(checkBalance==0)
							    			continue;
										list.add(res);
										checkSizeSubList++;
									}
								}else
									checkSizeSubList=0;
							}else if(TypePage=="CheckOutOnlySingle"||TypePage=="CheckOutPendingSingle"){
								if(r.getGroupIdString().equals("0")||r.getGroupIdString().equals("")){
									if(checkGroupSubList==0)
										continue;
									list.add(res);
								}else
									checkSizeSubList=0;
							}else if(TypePage=="CheckoutOnly"||TypePage=="CheckOutPending"||TypePage=="ExpressAll"){
								if(checkGroupSubList==0)
									continue;
								if(checkBalance==0&&TypePage=="ExpressAll")
					    			continue;
								list.add(res);
							}else
								list.add(res);
						}else{
							if(TypePage=="ExpressGroup"){
								if(!r.getGroupIdString().equals("0")||!r.getGroupIdString().equals("")){
									if(checkGroupSubList==0)
										continue;
									if(checkBalance==0)
						    			continue;
									list.add(res);
								}else
									checkSizeSubList=0;
							}else if(TypePage=="CheckOutOnlyGroup"||TypePage=="CheckOutPendingGroup"){
								if(nowDate.format(nowDate1).equals(nowDate.format(r.getDateTo()))){
									if(checkGroupSubList==0)
										continue;
									list.add(res);
								}else
									checkSizeSubList=0;
							}else if(TypePage=="ExpressSingle"){
								if(r.getGroupIdString().equals("0")||r.getGroupIdString().equals("")){
									if(((line*pointer)-checkSizeSubList)>0){
										if(checkBalance==0)
							    			continue;
										list.add(res);
										checkSizeSubList++;
									}
								}else
									checkSizeSubList=0;
							}else if(TypePage=="CheckOutOnlySingle"||TypePage=="CheckOutPendingSingle"){
								if(nowDate.format(nowDate1).equals(nowDate.format(r.getDateTo()))){
									if(checkGroupSubList==0)
										continue;
									list.add(res);
								}else
									checkSizeSubList=0;
							}else if(TypePage=="CheckoutOnly"||TypePage=="CheckOutPending"){
								if(nowDate.format(nowDate1).equals(nowDate.format(r.getDateTo()))){
									if(checkGroupSubList==0)
										continue;
									list.add(res);
								}else
									checkSizeSubList=0;
							}else{
								if(TypePage=="ExpressAll"){
									if(checkGroupSubList==0)
										continue;
									if(checkBalance==0)
						    			continue;
									list.add(res);
								}else
									list.add(res);
							}
						}
						CheckGroup = r.getGroupIdString();
					}
				}else{
					Double checkChargeFolio = 0.0;
					Double checkPaidFolio = 0.0;
					res.setTypePage(TypePage);
					res.setId(r.getId());
				    // set Folio status INV,IP INV balance = 0;
				    String FolioStringData = "";
				    if(r.getFolioListString()!=null){
				    	String[] ListArrayFolio = r.getFolioListString().split(",");
				    	 if(!ListArrayFolio.equals("")){
						    	for(int i = 0;i<ListArrayFolio.length;i++){
						    		long folioId = Long.parseLong(ListArrayFolio[i]);
						    		Folio foliodata = folioLogic.GetFolio(folioId);
						    		if(foliodata.isLock()==true){
						    			FolioStringData = "INV "+String.valueOf(foliodata.getId());
						    		}else{
						    			FolioStringData = "IP "+String.valueOf(foliodata.getId());
						    			for(int c = 0;c<foliodata.getCharge().size();c++){
						    				checkChargeFolio += foliodata.getCharge().get(c).getChargeAmount();
						    				//checkChargeFolio += foliodata.getCharge().get(c).getTax();
						    			}
						    			if(foliodata.getPaymentString()!=null)
							    			if(!foliodata.getPaymentString().equals("")){
							    				String [] subPaymentFolio = foliodata.getPaymentString().split(",");
							    				for(int p =0;p<subPaymentFolio.length;p++){
							    					long subpaymentId = Long.parseLong(subPaymentFolio[p]);
							    					SubPayment sp =  subPaymentLogic.GetSubPayment(subpaymentId);
							    					checkPaidFolio += sp.getAmount();
							    				}
							    			}
						    		}
						    	}
						    	res.setChargeFolio(checkChargeFolio);
						    	res.setPaidFolio(checkPaidFolio);
						    	res.setBalance(checkChargeFolio-checkPaidFolio);
						    	checkBalance = checkChargeFolio-checkPaidFolio;
						    	/*if(checkBalance==0){
						    		continue;
						    	}*/
						    }
				    }
				    res.setFolioId(FolioStringData);
				    FolioStringData = "";
					// set charge
				    String[] ListArrayCharge = r.getChargeListString().split(",");
				    String chargeAmount;
				    String chargeAmountTemp;
					for(int i = 0;i<ListArrayCharge.length;i++){
						Charge Ct = chargeLogic.GetCharge(Long.parseLong(ListArrayCharge[i]));
						if(Ct.isTemp()==false)
							sumAmountCharge += (Ct.getChargeAmount()+Ct.getTax());
						sumAmount += Ct.getChargeAmount();
					}
					
					if(r.getOtherChargeString()!=null&&!r.getOtherChargeString().equals("")){
						for(int k = 0;k<r.getOtherChargeList().size();k++){
							Charge OCt = r.getOtherChargeList().get(k);
							sumAmountCharge += (OCt.getChargeAmount()+OCt.getTax());
						}
					}
					chargeAmountTemp = String.valueOf(sumAmountCharge);
					chargeAmount = String.valueOf(sumAmount+(taxLogic.CalTax(hotelId,sumAmount)));
					res.setChargeCheckTemp(chargeAmountTemp);
					chargeAmountTemp = String.valueOf(sumAmountCharge);
					res.setDefaultCherge(sumAmount);
					res.setPaymentList(chargeAmount);
					sumAmountCharge = 0.0;
					// set payment
					PaymentLogic paymentLogic = new PaymentLogic(req,resp);
					String[] ListArrayPaymentList = r.getPaymentListString().split(",");
					if(!ListArrayPaymentList[0].equals("")){
						for(int i = 0;i<ListArrayPaymentList.length;i++){
							if(!ListArrayPaymentList[i].equals("")){
								Payment P = paymentLogic.GetPayment(Long.parseLong(ListArrayPaymentList[i]));
								sumAmountPayment += P.getAmount();
							}
						}
					}
					res.setPaymentAmount(sumAmountPayment);
					res.setTax(taxLogic.CalTax(hotelId,sumAmount));
					res.setTotaltax(sumAmount+(taxLogic.CalTax(hotelId,sumAmount)));
					res.setPracketPrice(r.getPackageByDate().get(0).getPackages().getName());
					sumAmount = 0.0;
					sumAmountPayment = 0.0;
					
					if(r.getSourcesString()!=null){
						SourcesBusiness S = new SourcesBusinessLogic().GetSourcesBusiness(Long.parseLong(r.getSourcesString()));
						res.setSourcesString(S.getTitle());
					}
					// set customer
					if(!r.getGuestString().equals("0")){
						String name = r.getGuest().getFirstName();
						String resId =String.valueOf(r.getId());
						if(SearchAll_checkoutPage!=null&&!SearchAll_checkoutPage.equals("")){
							if(SearchAll_checkoutPage.equals(name)){
								checkFilter = "true";
							}
							if(SearchAll_checkoutPage.equals(resId)){
								checkFilter = "true";
							}
							if(!checkFilter.equals("true")){
								checkFilter = "";
								continue;
							}
						}
						res.setName(r.getGuest().getFirstName() + " " + r.getGuest().getLastName());
						res.setGuestId(r.getGuest().getId());
						res.setPhone(r.getGuest().getPhone());
					}
					// set room
					res.setAssign(r.isAssign());
					res.setRoomName(r.getRoom().getRoomName());
					res.setRoomTypeName(r.getRoom().getRoomtype().getShortName());
					res.setRoomNameId(r.getRoom().getId());
					res.setRoomTypeId(r.getRoom().getRoomtype().getId());
					res.setDescription(r.getNote());
					res.setAdult(r.getAdult());
					res.setChild(r.getChild());
					// set Arrival
					res.setTravel(r.getTravelString());
					// set date
					res.setDate(r.getDate());
					res.setDateTo(r.getDateTo());
					res.setOrder(r.getOrder());
					res.setColor(r.getReservationStatus().getColor());
					res.setReservationTitle(r.getReservationStatus().getTitle());
					res.setSellRoom(r.getSellRoom());
					res.setSpan(r.getSpan());
					//set charge
					res.setOtherChargeList(r.getOtherChargeList());
					if(dateCheckout!=null&&!dateCheckout.equals("")){
						if(TypePage=="ExpressGroup"){
							if(!r.getGroupIdString().equals("0")&&!r.getGroupIdString().equals("")){
								if(((line*pointer)-checkSizeSubList)>0){
									if(checkBalance==0)
						    			continue;
									list.add(res);
									checkSizeSubList++;
								}
							}
						}else if(TypePage=="CheckOutOnlyGroup"||TypePage=="CheckOutPendingGroup"){
							if(!r.getGroupIdString().equals("0")&&!r.getGroupIdString().equals("")){
								if(((line*pointer)-checkSizeSubList)>0){
									list.add(res);
									checkSizeSubList++;
								}
							}
						}else if(TypePage=="ExpressSingle"){
							if(r.getGroupIdString().equals("0")||r.getGroupIdString().equals("")){
								if(((line*pointer)-checkSizeSubList)>0){
									if(checkBalance==0)
						    			continue;
									list.add(res);
									checkSizeSubList++;
								}
							}
						}else if(TypePage=="CheckOutOnlySingle"||TypePage=="CheckOutPendingSingle"){
							if(((line*pointer)-checkSizeSubList)>0){
								list.add(res);
								checkSizeSubList++;
							}
						}else if(TypePage=="CheckoutOnly"||TypePage=="CheckOutPending"||TypePage=="ExpressAll"){
							if(((line*pointer)-checkSizeSubList)>0){
								if(checkBalance==0&&TypePage=="ExpressAll")
					    			continue;
								list.add(res);
								checkSizeSubList++;
							}
						}else {
								list.add(res);
						}
					}else{
						if(TypePage=="ExpressGroup"){
							if(!r.getGroupIdString().equals("0")&&!r.getGroupIdString().equals("")){
								if(((line*pointer)-checkSizeSubList)>0){
									if(checkBalance==0)
						    			continue;
									list.add(res);
									checkSizeSubList++;
								}
							}
						}else if(TypePage=="CheckOutOnlyGroup"||TypePage=="CheckOutPendingGroup"){
							if(!r.getGroupIdString().equals("0")&&!r.getGroupIdString().equals("")){
								if(((line*pointer)-checkSizeSubList)>0){
									list.add(res);
									checkSizeSubList++;
								}
							}
						}else if(TypePage=="ExpressSingle"){
							if(r.getGroupIdString().equals("0")||r.getGroupIdString().equals("")){
								if(((line*pointer)-checkSizeSubList)>0){
									if(checkBalance==0)
						    			continue;
									list.add(res);
									checkSizeSubList++;
								}
							}
						}else if(TypePage=="CheckOutOnlySingle"||TypePage=="CheckOutPendingSingle"){
							if(nowDate.format(nowDate1).equals(nowDate.format(r.getDateTo()))){
								if(((line*pointer)-checkSizeSubList)>0){
									list.add(res);
									checkSizeSubList++;
								}
							}
						}else if(TypePage=="CheckoutOnly"||TypePage=="CheckOutPending"){
							if(nowDate.format(nowDate1).equals(nowDate.format(r.getDateTo()))){
								if(((line*pointer)-checkSizeSubList)>0){
									list.add(res);
									checkSizeSubList++;
								}
							}
						}else{
							if(TypePage=="ExpressAll"){
								if(((line*pointer)-checkSizeSubList)>0){
									if(checkBalance==0)
						    			continue;
									list.add(res);
									checkSizeSubList++;
								}
							}else{
								list.add(res);
							}
						}
					}
				}
			}
		}
		List<ReservationDataForReport> listForReturn = new ArrayList<ReservationDataForReport>();
		long countSizeAll = 0;
		long countSetToReturn = ((pointer-1)*line);
		long checkGroup = 0;
		long checkLine = 0;
		for(int i = 0;i<list.size();i++){
			long checkAddGroup = 0;
			if(list.get(i).subList!=null){
				if(pointer>1)
					checkAddGroup = list.get(i).subList.size()+(countSizeAll-(pointer-1)*line);
				else
					checkAddGroup = list.get(i).subList.size()+countSizeAll;
				if(checkAddGroup<=line&&countSizeAll>=countSetToReturn){
					if(checkLine<line){
						listForReturn.add(list.get(i));
						checkLine++;
					}
				}else{
					if(checkGroup==0){
						for(int j=0;j<list.get(i).subList.size();j++){
							countSizeAll++;
							if(countSizeAll>countSetToReturn){
								if(checkLine<line){
									listForReturn.add(list.get(i).subList.get(j));
									checkLine++;
								}
							}
						}
						if(listForReturn.size()>0){
							checkGroup = 1;
						}
					}else{
						if(checkLine<line){
							listForReturn.add(list.get(i));
							checkLine++;
						}
					}
				}
			}else{
				if(countSizeAll>=countSetToReturn){
					listForReturn.add(list.get(i));
				}
				countSizeAll++;
			}
		}
		return listForReturn;
	}
	
	public List<ReservationDataForReport> GetReservationAllReportCheckoutOnly(long hotelId,String TypePage,String dateCheckin , String dateCheckout,
			String SearchAll_checkoutPage)
			throws ParseException {
 		Double sumAmount = 0.0;
		Double sumAmountPayment = 0.0;
		Double sumAmountPaymentGroup = 0.0;
		Double sumAmountCharge = 0.0;
		List<ReservationDataForReport> list = new ArrayList<ReservationDataForReport>();
		List<Reservation> resvList;
		resvList = GetReservation_AllCheckoutOnly(hotelId,TypePage,dateCheckin,dateCheckout);
		Date nowDate1 = new GenericLogic(req,resp).ServerDateFromNightAudit(hotelId);
		SimpleDateFormat nowDate = new SimpleDateFormat("yyyyMMdd");
		String CheckGroup = "";
		TaxLogic taxLogic = new TaxLogic(req,resp);
		FolioLogic folioLogic= new FolioLogic(req,resp);
		ChargeLogic chargeLogic = new ChargeLogic(req,resp);
		PaymentLogic paymentLogic = new PaymentLogic(req,resp);
		SubPaymentLogic subPaymentLogic = new SubPaymentLogic(req,resp);
		Double checkBalance = 0.0;
		for (Reservation r : resvList) {
			Double checkChargeFolioGroup = 0.0;
			Double checkPaidFolioGroup = 0.0;
			String FolioStringDataGroup = "";
			String checkFilter = "";
			List<ReservationDataForReport> sublist = new ArrayList<ReservationDataForReport>();
			ReservationDataForReport res = new ReservationDataForReport();
				if(r.getGroupIdNumber()!=0){
					// set reservation in group
					String[] ArrayResvList = r.getGroupId().getListResvString().split(",");
					for(int i = 0;i<ArrayResvList.length;i++){
						ReservationDataForReport Subres = new ReservationDataForReport();
						Reservation rsv = GetReservation(Long.parseLong(ArrayResvList[i].trim()));
						Double checkChargeFolioSubRes = 0.0;
						Double checkPaidFolioSubRes = 0.0;
						String FolioStringDataSubRes = "";
							if(r.getFolioListString()!=null){
					    	String[] ListArrayFolio = rsv.getFolioListString().split(",");
						    if(!ListArrayFolio.equals("")){
						    	for(int f = 0;f<ListArrayFolio.length;f++){
						    		long folioId = Long.parseLong(ListArrayFolio[f]);
						    		Folio foliodata = folioLogic.GetFolio(folioId);
						    		if(foliodata.isLock()==true){
						    			FolioStringDataSubRes = "INV "+String.valueOf(foliodata.getId());
						    		}else{
						    			FolioStringDataSubRes = "IP "+String.valueOf(foliodata.getId());
						    			for(int c = 0;c<foliodata.getCharge().size();c++){
						    				checkChargeFolioSubRes += foliodata.getCharge().get(c).getChargeAmount();
						    			}
						    			if(foliodata.getPaymentString()!=null)
							    			if(!foliodata.getPaymentString().equals("")){
							    				String [] subPaymentFolio = foliodata.getPaymentString().split(",");
							    				for(int p =0;p<subPaymentFolio.length;p++){
							    					long subpaymentId = Long.parseLong(subPaymentFolio[p]);
							    					SubPayment sp =  subPaymentLogic.GetSubPayment(subpaymentId);
							    					checkPaidFolioSubRes += sp.getAmount();
							    				}
							    			}
						    		}
						    		FolioStringDataGroup += FolioStringDataSubRes+",<br>";
						    	}
						    	checkChargeFolioGroup += checkChargeFolioSubRes;
						    	checkPaidFolioGroup   += checkPaidFolioSubRes;
						    	Subres.setChargeFolio(checkChargeFolioSubRes);
						    	Subres.setPaidFolio(checkPaidFolioSubRes);
						    	Subres.setBalance(checkChargeFolioSubRes-checkPaidFolioSubRes);
						    	checkBalance = checkChargeFolioSubRes-checkPaidFolioSubRes;
						    }
						    Subres.setFolioId(FolioStringDataSubRes);
						    FolioStringDataSubRes="";
					    }
						Subres.setGroupId(rsv.getGroupIdNumber());
						Subres.setId(rsv.getId());
						String[] ListArrayCharge = rsv.getChargeListString().split(",");
						
						String[] ListArrayPaymentList = rsv.getPaymentListString().split(",");
					    String chargeAmount;
					    String chargeAmountTemp;
					    // set Folio status INV,IP INV balance = 0;
					    String FolioStringData_ResIngroup = "";
					    if(rsv.getFolioListString()!=null){
					    	String[] ListArrayFolio = rsv.getFolioListString().split(",");
						    if(!ListArrayFolio.equals("")){
						    	for(int f = 0;f<ListArrayFolio.length;f++){
						    		long folioId = Long.parseLong(ListArrayFolio[f]);
						    		Folio foliodata = folioLogic.GetFolio(folioId);
						    		
						    		if(foliodata.isLock()==true){
						    			FolioStringData_ResIngroup = "INV "+String.valueOf(foliodata.getId());
						    		}else{
						    			FolioStringData_ResIngroup = "IP "+String.valueOf(foliodata.getId());
						    		}
						    	}
						    }
					    }
					    Subres.setFolioId(FolioStringData_ResIngroup);
					    FolioStringData_ResIngroup="";
						// set charge
						for(int j = 0;j<ListArrayCharge.length;j++){
							Charge Ct = chargeLogic.GetCharge(Long.parseLong(ListArrayCharge[j]));
							if(Ct.isTemp()==false)
								sumAmountCharge += (Ct.getChargeAmount()+Ct.getTax());
							sumAmount += Ct.getChargeAmount();
						}
						if(rsv.getOtherChargeString()!=null&&!rsv.getOtherChargeString().equals("")){
							for(int k = 0;k<rsv.getOtherChargeList().size();k++){
								Charge OCt = rsv.getOtherChargeList().get(k);
								sumAmountCharge += (OCt.getChargeAmount()+OCt.getTax());
							}
						}
						chargeAmountTemp = String.valueOf(sumAmountCharge);
						chargeAmount = String.valueOf(sumAmount+(taxLogic.CalTax(hotelId,sumAmount)));
						Subres.setChargeCheckTemp(chargeAmountTemp);
						Subres.setDefaultCherge(sumAmount);
						Subres.setTax(taxLogic.CalTax(hotelId,sumAmount));
						Subres.setTotaltax(sumAmount+(taxLogic.CalTax(hotelId,sumAmount)));
						sumAmountCharge = 0.0;
						// set payment
						if(!ListArrayPaymentList[0].equals("")){
							for(int j = 0;j<ListArrayPaymentList.length;j++){
								String paymentIdString = String.valueOf(ListArrayPaymentList[j]);
								if(!paymentIdString.equals("")){
									Payment P = paymentLogic.GetPayment(Long.parseLong(paymentIdString));
									sumAmountPayment += P.getAmount();
								}
							}
						}
						Subres.setPaymentAmount(sumAmountPayment);
						Subres.setPaymentList(chargeAmount);
						Subres.setPracketPrice(rsv.getPackageByDate().get(0).getPackages().getName());
						sumAmount = 0.0;
						sumAmountPayment = 0.0;
						// set customer
						if(rsv.getSourcesString()!=null){
							SourcesBusiness S = new SourcesBusinessLogic().GetSourcesBusiness(Long.parseLong(rsv.getSourcesString()));
							Subres.setSourcesString(S.getTitle());
						}
						// set customer
						if(!rsv.getGuestString().equals("0")){
							Subres.setName(rsv.getGuest().getFirstName() +" "+ rsv.getGuest().getLastName());
							Subres.setGuestId(rsv.getGuest().getId());
							Subres.setPhone(rsv.getGuest().getPhone());
						}
						// set room
						Subres.setAssign(rsv.isAssign());
						Subres.setRoomName(rsv.getRoom().getRoomName());
						Subres.setRoomTypeName(rsv.getRoom().getRoomtype().getShortName());
						Subres.setRoomNameId(rsv.getRoom().getId());
						Subres.setRoomTypeId(rsv.getRoom().getRoomtype().getId());
						Subres.setAdult(rsv.getAdult());
						Subres.setChild(rsv.getChild());
						Subres.setDescription(rsv.getNote());
						Subres.setSellRoom(rsv.getSellRoom());
						Subres.setSpan(rsv.getSpan());
						// set date
						Subres.setDate(rsv.getDate());
						Subres.setDateTo(rsv.getDateTo());
						Subres.setOrder(rsv.getOrder());
						Subres.setColor(rsv.getReservationStatus().getColor());
						Subres.setReservationTitle(rsv.getReservationStatus().getTitle());
						// set chargeOther
						Subres.setOtherChargeList(rsv.getOtherChargeList());
						// set chargeList
						Subres.setChargeList(rsv.getChargeList());
						sublist.add(Subres);
					}
					res.setSubList(sublist);
					//end set reservation in group
					res.setChargeFolio(checkChargeFolioGroup);
					res.setPaidFolio(checkPaidFolioGroup);
					res.setBalance(checkChargeFolioGroup-checkPaidFolioGroup);
					if(!FolioStringDataGroup.equals(""))
						res.setFolioId(FolioStringDataGroup.substring(0, FolioStringDataGroup.length()-5));
				
					res.setTypePage(TypePage);
					if(!CheckGroup.equals(r.getGroupIdString())){
						res.setResLis(r.getGroupId().getListResvString());
						res.setGroupIdString(r.getGroupIdString());
						res.setGroupId(r.getGroupIdNumber());
						res.setId(r.getId());
						r.getGroupId().getPaymentListString().split(",");
						// payment
						String[] ListArrayPaymentListGroup = r.getGroupId().getPaymentListString().split(",");
						for(int j = 0;j<ListArrayPaymentListGroup.length;j++){
							String paymentIdStringGroup = String.valueOf(ListArrayPaymentListGroup[j]);
							if(!paymentIdStringGroup.equals("")){
								Payment P = paymentLogic.GetPayment(Long.parseLong(paymentIdStringGroup));
								sumAmountPaymentGroup += P.getAmount();
							}
						}
						res.setPaymentAmount(sumAmountPaymentGroup);
						sumAmountPaymentGroup = 0.0;
						// set customer
						if(r.getGroupId().getGuest()!=null){
							String name = r.getGroupId().getGuest().getFirstName();
							String groupId =String.valueOf(r.getGroupId().getId());
							if(SearchAll_checkoutPage!=null&&!SearchAll_checkoutPage.equals("")){
								String firstStringSearch = SearchAll_checkoutPage.substring(0,1);
								if(firstStringSearch.equals("G")||firstStringSearch.equals("g"))
									SearchAll_checkoutPage = SearchAll_checkoutPage.substring(1,SearchAll_checkoutPage.length());
								if(SearchAll_checkoutPage.equals(name)){
									checkFilter = "true";
								}
								if(SearchAll_checkoutPage.equals(groupId)){
									checkFilter = "true";
								}
								if(!checkFilter.equals("true"))
									continue;
							}
							res.setName(r.getGroupId().getGuest().getFirstName() +" "+r.getGroupId().getGuest().getLastName());
							res.setGuestId(r.getGroupId().getGuest().getId());
							res.setPhone(r.getGroupId().getGuest().getPhone());
						}else{
							res.setName("");
						}
						// set room
						res.setPhone(r.getGroupId().getGuest().getPhone());
						res.setDescription(r.getGroupId().getNote());
						res.setAssign(r.isAssign());
						res.setRoomName(r.getRoom().getRoomName());
						res.setRoomTypeName(r.getRoom().getRoomtype().getShortName());
						res.setRoomNameId(r.getRoom().getId());
						res.setRoomTypeId(r.getRoom().getRoomtype().getId());
						// set date
						res.setDate(r.getDate());
						res.setDateTo(r.getDateTo());
						res.setOrder(r.getOrder());
						res.setColor(r.getReservationStatus().getColor());
						res.setReservationTitle(r.getReservationStatus().getTitle());
						res.setSellRoom(r.getSellRoom());
						res.setSpan(r.getGroupId().getSpan());
						// set charge
						res.setOtherChargeList(r.getGroupId().getOtherChargeList());
						res.setChargeList(r.getGroupId().getChargeList());
						
						if(dateCheckout!=null&&!dateCheckout.equals("")){
							if(TypePage=="ExpressGroup"||TypePage=="ExpressSingle"||TypePage=="ExpressAll"||TypePage=="ExpressAllCount"){
								if(checkBalance==0)
					    			continue;
								list.add(res);
							}else if(TypePage=="CheckOutPending"||TypePage=="CheckOutPendingSingle"||TypePage=="CheckOutPendingGroup"||TypePage=="CheckOutPendingCount"||TypePage=="CheckoutOnly"||TypePage=="CheckoutOnlyCount"||TypePage=="CheckOutOnlySingle"||TypePage=="CheckOutOnlyGroup")
								list.add(res);
						}else{
							if(TypePage=="ExpressGroup"||TypePage=="ExpressSingle"||TypePage=="ExpressAll"||TypePage=="ExpressAllCount"){
								if(checkBalance==0)
					    			continue;
								list.add(res);
							}else if(TypePage=="CheckOutPending"||TypePage=="CheckOutPendingSingle"||TypePage=="CheckOutPendingGroup"||TypePage=="CheckOutPendingCount"||TypePage=="CheckoutOnly"||TypePage=="CheckoutOnlyCount"||TypePage=="CheckOutOnlyGroup"||TypePage=="CheckOutOnlySingle")
								if(nowDate.format(nowDate1).equals(nowDate.format(r.getDateTo())))
									list.add(res);
						}
						CheckGroup = r.getGroupIdString();
					}
				}else{
					Double checkChargeFolio = 0.0;
					Double checkPaidFolio = 0.0;
					res.setTypePage(TypePage);
					res.setId(r.getId());
				    // set Folio status INV,IP INV balance = 0;
				    String FolioStringData = "";
				    if(r.getFolioListString()!=null){
				    	String[] ListArrayFolio = r.getFolioListString().split(",");
					    if(!ListArrayFolio.equals("")){
					    	for(int i = 0;i<ListArrayFolio.length;i++){
					    		long folioId = Long.parseLong(ListArrayFolio[i]);
					    		Folio foliodata = folioLogic.GetFolio(folioId);
					    		if(foliodata.isLock()==true){
					    			FolioStringData = "INV "+String.valueOf(foliodata.getId());
					    		}else{
					    			FolioStringData = "IP "+String.valueOf(foliodata.getId());
					    			for(int c = 0;c<foliodata.getCharge().size();c++){
					    				checkChargeFolio += foliodata.getCharge().get(c).getChargeAmount();
					    				//checkChargeFolio += foliodata.getCharge().get(c).getTax();
					    			}
					    			if(foliodata.getPaymentString()!=null)
						    			if(!foliodata.getPaymentString().equals("")){
						    				String [] subPaymentFolio = foliodata.getPaymentString().split(",");
						    				for(int p =0;p<subPaymentFolio.length;p++){
						    					long subpaymentId = Long.parseLong(subPaymentFolio[p]);
						    					SubPayment sp =  subPaymentLogic.GetSubPayment(subpaymentId);
						    					checkPaidFolio += sp.getAmount();
						    				}
						    			}
					    		}
					    	}
					    	res.setChargeFolio(checkChargeFolio);
					    	res.setPaidFolio(checkPaidFolio);
					    	res.setBalance(checkChargeFolio-checkPaidFolio);
					    	checkBalance = checkChargeFolio-checkPaidFolio;
					    	/*if(checkBalance==0){
					    		continue;
					    	}*/
					    }
				    }
				    res.setFolioId(FolioStringData);
				    FolioStringData = "";
					// set charge
				    String[] ListArrayCharge = r.getChargeListString().split(",");
				    String chargeAmount;
				    String chargeAmountTemp;
					for(int i = 0;i<ListArrayCharge.length;i++){
						Charge Ct = chargeLogic.GetCharge(Long.parseLong(ListArrayCharge[i]));
						if(Ct.isTemp()==false)
							sumAmountCharge += (Ct.getChargeAmount()+Ct.getTax());
						sumAmount += Ct.getChargeAmount();
					}
					
					if(r.getOtherChargeString()!=null&&!r.getOtherChargeString().equals("")){
						for(int k = 0;k<r.getOtherChargeList().size();k++){
							Charge OCt = r.getOtherChargeList().get(k);
							sumAmountCharge += (OCt.getChargeAmount()+OCt.getTax());
						}
					}
					chargeAmountTemp = String.valueOf(sumAmountCharge);
					chargeAmount = String.valueOf(sumAmount+(taxLogic.CalTax(hotelId,sumAmount)));
					res.setChargeCheckTemp(chargeAmountTemp);
					chargeAmountTemp = String.valueOf(sumAmountCharge);
					res.setDefaultCherge(sumAmount);
					res.setPaymentList(chargeAmount);
					sumAmountCharge = 0.0;
					res.setTax(taxLogic.CalTax(hotelId,sumAmount));
					res.setTotaltax(sumAmount+(taxLogic.CalTax(hotelId,sumAmount)));
					res.setPracketPrice(r.getPackageByDate().get(0).getPackages().getName());
					sumAmount = 0.0;
					sumAmountPayment = 0.0;
					// set customer
					if(!r.getGuestString().equals("0")){
						String name = r.getGuest().getFirstName();
						String resId =String.valueOf(r.getId());
						if(SearchAll_checkoutPage!=null&&!SearchAll_checkoutPage.equals("")){
							if(SearchAll_checkoutPage.equals(name)){
								checkFilter = "true";
							}
							if(SearchAll_checkoutPage.equals(resId)){
								checkFilter = "true";
							}
							if(!checkFilter.equals("true")){
								checkFilter = "";
								continue;
							}
						}
						res.setName(r.getGuest().getFirstName() + " " + r.getGuest().getLastName());
						res.setGuestId(r.getGuest().getId());
						res.setPhone(r.getGuest().getPhone());
					}
					// set room
					res.setAssign(r.isAssign());
					res.setRoomName(r.getRoom().getRoomName());
					res.setRoomTypeName(r.getRoom().getRoomtype().getShortName());
					res.setRoomNameId(r.getRoom().getId());
					res.setRoomTypeId(r.getRoom().getRoomtype().getId());
					res.setDescription(r.getNote());
					res.setAdult(r.getAdult());
					res.setChild(r.getChild());
					//set Arrival
					res.setTravel(r.getTravelString());
					// set date
					res.setDate(r.getDate());
					res.setDateTo(r.getDateTo());
					res.setOrder(r.getOrder());
					res.setColor(r.getReservationStatus().getColor());
					res.setReservationTitle(r.getReservationStatus().getTitle());
					res.setSellRoom(r.getSellRoom());
					res.setSpan(r.getSpan());
					res.setChargeList(r.getChargeList());
					res.setOtherChargeList(r.getOtherChargeList());
					// set payment
					double sumPayment = 0;
					if(r.getPaymentList()!=null)
						for(int i = 0;i<r.getPaymentList().size();i++){
							sumPayment += r.getPaymentList().get(i).getAmount();
						}
					res.setPaymentAmount(sumPayment);
					res.setPayment(r.getPaymentList());
					if(dateCheckout!=null&&!dateCheckout.equals("")){
						if(TypePage=="ExpressSingle"||TypePage=="ExpressAll"||TypePage=="ExpressAllCount"){
							if(checkBalance==0)
				    			continue;
							list.add(res);
						}else if(TypePage=="CheckOutPending"||TypePage=="CheckOutPendingSingle"||TypePage=="CheckOutPendingGroup"||TypePage=="CheckOutPendingCount"||TypePage=="CheckoutOnly"||TypePage=="CheckoutOnlyCount"||TypePage=="CheckOutOnlySingle")
							list.add(res);
					}else{
						if(TypePage=="ExpressSingle"||TypePage=="ExpressAll"||TypePage=="ExpressAllCount"){
							if(checkBalance==0)
				    			continue;
							list.add(res);
						}else if(TypePage=="CheckOutPending"||TypePage=="CheckOutPendingSingle"||TypePage=="CheckOutPendingGroup"||TypePage=="CheckOutPendingCount"||TypePage=="CheckoutOnly"||TypePage=="CheckoutOnlyCount"||TypePage=="CheckOutOnlySingle")
							if(nowDate.format(nowDate1).equals(nowDate.format(r.getDateTo())))
								list.add(res);
					}
				}
		}
		return list;
	}
	/////	
public List<ReservationDataForReport> GetReservationAllReport(long hotelId,String TypePage,String dateCheckin , String dateCheckout, String typeReservation,
		String SearchAll_checkoutPage)
			throws ParseException {
		List<ReservationDataForReport> list = new ArrayList<ReservationDataForReport>();
		Double sumAmount = 0.0;
		Double sumAmountPayment = 0.0;
		Double sumAmountCharge = 0.0;
		Double sumAmountCharegeGroup = 0.0;
		Double paymentGroup = 0.0;
		List<Reservation> resvList;
		if(TypePage == "CheckIn"||TypePage == "CheckInCount"){
			resvList = GetReservation_Report(hotelId,"CheckIn","","","");
		}else if(TypePage == "CheckInPending"|| TypePage == "CheckInPendingCount"|| TypePage == "CheckInPendingSingle"||TypePage == "CheckInPendingGroup"){
			 if(TypePage == "CheckInPendingSingle"){
				resvList = GetReservation_Report(hotelId,"CheckInPendingSingle",dateCheckin,dateCheckout,"");
			}else if(TypePage == "CheckInPendingGroup"){
				resvList = GetReservation_Report(hotelId,"CheckInPendingGroup",dateCheckin,dateCheckout,"");
			}else{
				resvList = GetReservation_Report(hotelId,"CheckInPending",dateCheckin,dateCheckout,"");
			}
		}else if(TypePage == "Deposits"|| TypePage == "DepositsCount"|| TypePage == "DepositsSingle"||TypePage == "DepositsGroup"){
			 if(TypePage == "DepositsSingle"){
				resvList = GetReservation_Report(hotelId,"DepositsSingle",dateCheckin,dateCheckout,"");
			}else if(TypePage == "DepositsGroup"){
				resvList = GetReservation_Report(hotelId,"DepositsGroup",dateCheckin,dateCheckout,"");
			}else{
				resvList = GetReservation_Report(hotelId,"Deposits",dateCheckin,dateCheckout,"");
			}
		}else if(TypePage == "Temp"|| TypePage == "TempCount"|| TypePage == "TempSingle"||TypePage == "TempGroup"){
			if(TypePage == "TempGroup"){
				resvList = GetReservation_Report(hotelId,"TempGroup",dateCheckin,dateCheckout,"");
			}else if(TypePage == "TempSingle"){
				resvList = GetReservation_Report(hotelId,"TempSingle",dateCheckin,dateCheckout,"");
			}else{
				resvList = GetReservation_Report(hotelId,"Temp",dateCheckin,dateCheckout,"");
			}
		}else if(TypePage == "CancelResv"|| TypePage == "CancelResvCount"|| TypePage == "CancelResvSingle"||TypePage == "CancelResvGroup"){
			if(TypePage == "CancelResvSingle"){
				resvList = GetReservation_Report(hotelId,"CancelResvSingle",dateCheckin,dateCheckout,"");
			}else if(TypePage == "CancelResvGroup"){
				resvList = GetReservation_Report(hotelId,"CancelResvGroup",dateCheckin,dateCheckout,"");
			}else{
				resvList = GetReservation_Report(hotelId,"CancelResv",dateCheckin,dateCheckout,"");
			}
		}else if(TypePage == "NoShow"|| TypePage == "NoShowCount"|| TypePage == "NoShowSingle"||TypePage == "NoShowGroup"){
			if(TypePage == "NoShowSingle"){
				resvList = GetReservation_Report(hotelId,"NoShowSingle",dateCheckin,dateCheckout,"");
			}else if(TypePage == "NoShowGroup"){
				resvList = GetReservation_Report(hotelId,"NoShowGroup",dateCheckin,dateCheckout,"");
			}else{
				resvList = GetReservation_Report(hotelId,"NoShow",dateCheckin,dateCheckout,"");
			}
		}else if(TypePage == "CheckOutPending"|| TypePage == "CheckOutPendingCount"|| TypePage == "CheckOutPendingSingle"||TypePage == "CheckOutPendingGroup"){
			if(TypePage == "CheckOutPendingSingle"){
				resvList = GetReservation_Report(hotelId,"CheckOutPendingSingle","","","");
			}else if(TypePage == "CheckOutPendingGroup"){
				resvList = GetReservation_Report(hotelId,"CheckOutPendingGroup","","","");
			}else{
				resvList = GetReservation_Report(hotelId,"CheckOutPending","","","");
			}
		}else if(TypePage == "PaymentTracker"|| TypePage == "PaymentTrackerCount"|| TypePage == "PaymentTrackerSingle"||TypePage == "PaymentTrackerGroup"){
			if(TypePage == "PaymentTrackerSingle"){
				resvList = GetReservation_Report(hotelId,"PaymentTrackerSingle",dateCheckin,dateCheckout,"");
			}else if(TypePage == "PaymentTrackerGroup"){
				resvList = GetReservation_Report(hotelId,"PaymentTrackerGroup",dateCheckin,dateCheckout,"");
			}else{
				resvList = GetReservation_Report(hotelId,"PaymentTracker",dateCheckin,dateCheckout,"");
			}
		}else if(TypePage == "GuestName"|| TypePage == "GuestNameCount"|| TypePage == "GuestNameSingle"||TypePage == "GuestNameGroup"){
			if(TypePage == "GuestNameSingle"){
				resvList = GetReservation_Report(hotelId,"GuestNameSingle",dateCheckin,dateCheckout,typeReservation);
			}else if(TypePage == "GuestNameGroup"){
				resvList = GetReservation_Report(hotelId,"GuestNameGroup",dateCheckin,dateCheckout,typeReservation);
			}else{
				if(typeReservation==null||typeReservation.equals(""))
					typeReservation="reservationType_A";
				resvList = GetReservation_Report(hotelId,"GuestName",dateCheckin,dateCheckout,typeReservation);
			}
		}else if(TypePage == "All"|| TypePage == "AllCount"|| TypePage == "AllSingle"||TypePage == "AllGroup"){
			if(TypePage == "AllSingle"){
				resvList = GetReservation_Report(hotelId,"AllSingle",dateCheckin,dateCheckout,typeReservation);
			}else if(TypePage == "AllGroup"){
				resvList = GetReservation_Report(hotelId,"AllGroup",dateCheckin,dateCheckout,typeReservation);
			}else{
				resvList = GetReservation_Report(hotelId,"All",dateCheckin,dateCheckout,typeReservation);
			}
		}else{
			resvList = GetReservation_Report(hotelId,"CheckIn","","","");
		}
		Date nowDate1 = new GenericLogic(req,resp).ServerDateTime(hotelId);
		SimpleDateFormat nowDate = new SimpleDateFormat("yyyyMMdd");
		String CheckGroup = "";
		String CheckGroupDouble = "";
		TaxLogic taxLogic = new TaxLogic(req,resp);
		ChargeLogic chargeLogic = new ChargeLogic(req,resp);
		for (Reservation r : resvList) {
		String checkFilter = "";
		List<ReservationDataForReport> sublist = new ArrayList<ReservationDataForReport>();
		ReservationDataForReport res = new ReservationDataForReport();
			if(r.getGroupIdNumber()!=0){
				if(!CheckGroup.equals(r.getGroupIdString())){
					if(list.size()!=0){
                		for(int l =0;l<list.size();l++){
	                		if(list.get(l).getGroupId()==r.getGroupIdNumber()){
	                			CheckGroupDouble = "1";
	                		}
	                	}
                	}
                	if(CheckGroupDouble=="1"){
                		CheckGroupDouble = "";
                		continue;
                	}
					res.setTypePage(TypePage);
					res.setReservationTitle(r.getReservationStatus().getTitle());
					//set Agency group
					if(r.getAgencyIdString()!=null&&!r.getAgencyIdString().equals("0")){ 
						Agency obj = new AgencyLogic(req,resp).GetAgency(Long.parseLong(r.getAgencyIdString()));
						res.setAgencyString(obj.getAgency());
					}
					//set customer group
                    String[] splitResId = r.getGroupId().getListResvString().split(",");
					for(int i =0;i<splitResId.length;i++){
						if(SearchAll_checkoutPage!=null)
							if(SearchAll_checkoutPage.equals(splitResId[i].trim()))
								checkFilter = "true";
					}
                    if (r.getGroupId().getGuest() != null) {
                    	String name = r.getGroupId().getGuest().getFirstName();
						String groupId =String.valueOf(r.getGroupId().getId());
						if(SearchAll_checkoutPage!=null&&!SearchAll_checkoutPage.equals("")){
							String firstStringSearch = SearchAll_checkoutPage.substring(0,1);
							if(firstStringSearch.equals("G")||firstStringSearch.equals("g"))
								SearchAll_checkoutPage = SearchAll_checkoutPage.substring(1,SearchAll_checkoutPage.length());
							if(SearchAll_checkoutPage.equals(name)){
								checkFilter = "true";
							}
							if(SearchAll_checkoutPage.equals(groupId)){
								checkFilter = "true";
							}
							if(!checkFilter.equals("true"))
								continue;
						}
                        res.setName(r.getGroupId().getGuest().getFirstName() + " " + r.getGroupId().getGuest().getLastName());
                        res.setGuestId(r.getGroupId().getGuest().getId());
                        res.setPhone(r.getGroupId().getGuest().getPhone());
                        res.setEmail(r.getGroupId().getGuest().getMail());
                    } else {
                        res.setName("");
                    }
					//set payment group
					PaymentLogic paymentLogic = new PaymentLogic(req,resp);
					String[] ListPaymentGroup = r.getGroupId().getPaymentListString().split(",");
					if(!ListPaymentGroup[0].equals("")){
						for(int p =0;p<ListPaymentGroup.length;p++){
							long paymentIdStirng =  Long.parseLong(ListPaymentGroup[p]);
							Payment paymentData = paymentLogic.GetPayment(paymentIdStirng);
							paymentGroup += paymentData.getAmount();
						}
					}
					res.setPaymentAmount(paymentGroup);
					if(TypePage == "DepositsCount"){
					    if(paymentGroup<=0){continue;}
					}
					//setCharge group
					String chargeAmountTempGroup = "";
					String[] ListArrayChargeGroup = r.getChargeListString().split(",");
					for(int cg = 0;cg<ListArrayChargeGroup.length;cg++){ 
						Charge Ct = chargeLogic.GetCharge(Long.parseLong(ListArrayChargeGroup[cg]));
						if(Ct!=null){
							if(Ct.isTemp()==false)
								sumAmountCharge += (Ct.getChargeAmount()+Ct.getTax());
							if(Ct.isRoomCharge()==false)
								sumAmountCharge += (Ct.getChargeAmount()+Ct.getTax());
						}
					}
					if(r.getGroupId().getOtherChargeString()!=null&&!r.getGroupId().getOtherChargeString().equals("")){
						for(int k = 0;k<r.getGroupId().getOtherChargeList().size();k++){
							Charge OCt = r.getGroupId().getOtherChargeList().get(k);
							sumAmountCharge += (OCt.getChargeAmount()+OCt.getTax());
						}
					}
					chargeAmountTempGroup = String.valueOf(sumAmountCharge);
					res.setChargeCheckTemp(chargeAmountTempGroup);
					if(sumAmountCharge>0){
						res.setAfterNightChargeRoom(sumAmountCharge-paymentGroup);
					}else{
						res.setAfterNightChargeRoom(sumAmountCharge);
					}
					sumAmountCharge = 0.0;
					//set Group group
					res.setGroupIdString(r.getGroupIdString());
					res.setGroupId(r.getGroupIdNumber());
					res.setId(r.getId());
					res.setDisplayId(r.getDisplayId());
					res.setDescription(r.getGroupId().getNote());
					res.setResLis(r.getGroupId().getListResvString());
					//set Room group
					res.setAssign(r.isAssign());
					res.setRoomName(r.getRoom().getRoomName());
					res.setRoomTypeName(r.getRoom().getRoomtype().getShortName());
					res.setRoomNameId(r.getRoom().getId());
					res.setRoomTypeId(r.getRoom().getRoomtype().getId());
					//set Date group
					res.setDate(r.getDate());
					res.setDateTo(r.getDateTo());
					res.setOrder(r.getOrder());
					res.setSellRoom(r.getSellRoom());
					res.setColor(r.getReservationStatus().getColor());
					res.setSpan(r.getGroupId().getSpan());
					// reservation in group
					String[] ArrayResvList = r.getGroupId().getListResvString().split(",");
					for(int i = 0;i<ArrayResvList.length;i++){ 
						ReservationDataForReport Subres = new ReservationDataForReport();
						Reservation rsv = null;
						if(!ArrayResvList[i].trim().equals("null")){
							 rsv = GetReservation(Long.parseLong(ArrayResvList[i].trim()));
						}else{
							continue;
						}
						Subres.setGroupId(rsv.getGroupIdNumber());
						Subres.setId(rsv.getId());
						Subres.setDisplayId(rsv.getDisplayId());
						//set status Room
						Subres.setCleaningStatus(rsv.getRoom().getCleaningStatus().getTitle());
						//set reason
						String[] ListArrayCharge = rsv.getChargeListString().split(",");
						String[] ListArrayPaymentList = rsv.getPaymentListString().split(",");
					    String chargeAmount;
					    String chargeAmountTemp;
					    //set charge res in group
						for(int j = 0;j<ListArrayCharge.length;j++){
							String chargeIdString = String.valueOf(ListArrayCharge[j]);
							Charge Ct = chargeLogic.GetCharge(Long.parseLong(chargeIdString));
							if(Ct!=null){
								if(Ct.isTemp()==false)
									sumAmountCharge += (Ct.getChargeAmount()+Ct.getTax());
								if(Ct.isRoomCharge()==false)
									sumAmountCharge += (Ct.getChargeAmount()+Ct.getTax());
							}
							if(Ct!=null)
								sumAmount += Ct.getChargeAmount();
						}
						if(rsv.getOtherChargeString()!=null&&!rsv.getOtherChargeString().equals("")){
							String reasonCancelString = "";
							for(int k = 0;k<rsv.getOtherChargeList().size();k++){
								Charge OCt = rsv.getOtherChargeList().get(k);
								sumAmountCharge += (OCt.getChargeAmount()+OCt.getTax());
								if(OCt.getReasondetailId()!=0){
									ReasonDetail reasonC = new ReasonDetailLogic().GetReasonDetail(OCt.getReasondetailId());
									reasonCancelString = reasonC.getReasonString();
								}
							}
							Subres.setReasoncancelString(reasonCancelString);
						}
						sumAmountCharegeGroup += sumAmount+(taxLogic.CalTax(hotelId,sumAmount));
						chargeAmountTemp = String.valueOf(sumAmountCharge);
						chargeAmount = String.valueOf(sumAmount+(taxLogic.CalTax(hotelId,sumAmount)));
						Subres.setDefaultCherge(sumAmount);
						Subres.setChargeCheckTemp(chargeAmountTemp);
						Subres.setPaymentList(chargeAmount);
						Subres.setAfterNightChargeRoom(sumAmountCharge);
						//set payment res in group
						if(!ListArrayPaymentList[0].equals("")){
							for(int j = 0;j<ListArrayPaymentList.length;j++){
								String paymentIdString = String.valueOf(ListArrayPaymentList[j]);
								if(!paymentIdString.equals("")){
									Payment P = paymentLogic.GetPayment(Long.parseLong(paymentIdString));
									sumAmountPayment += P.getAmount();
								}
							}
						}
						Subres.setTax(taxLogic.CalTax(hotelId,sumAmount));
						Subres.setTotaltax(sumAmount+(taxLogic.CalTax(hotelId,sumAmount)));
						Subres.setBalance(sumAmount+(taxLogic.CalTax(hotelId,sumAmount))-sumAmountPayment);
						Subres.setPracketPrice(rsv.getPackageByDate().get(0).getPackages().getName());
						Subres.setPaymentAmount(sumAmountPayment);
						sumAmountPayment = 0.0;
						sumAmount = 0.0;
						sumAmountCharge = 0.0;
						// set customer res in group
						if(rsv.getSourcesString()!=null){
							SourcesBusiness S = new SourcesBusinessLogic().GetSourcesBusiness(Long.parseLong(rsv.getSourcesString()));
							Subres.setSourcesString(S.getTitle());
						}
						if(rsv.getAgencyIdString()!=null&&!rsv.getAgencyIdString().equals("0")){
							Agency obj = new AgencyLogic(req,resp).GetAgency(Long.parseLong(rsv.getAgencyIdString()));
							Subres.setAgencyString(obj.getAgency());
						}
						if(!rsv.getGuestString().equals("0")){
							Subres.setName(rsv.getGuest().getFirstName() +" "+ rsv.getGuest().getLastName());
							Subres.setGuestId(rsv.getGuest().getId());
							Subres.setPhone(rsv.getGuest().getPhone());
							Subres.setEmail(rsv.getGuest().getMail());
						}
						// set room res in group
						Subres.setAssign(rsv.isAssign());
						Subres.setRoomName(rsv.getRoom().getRoomName());
						Subres.setRoomTypeName(rsv.getRoom().getRoomtype().getShortName());
						Subres.setRoomNameId(rsv.getRoom().getId());
						Subres.setRoomTypeId(rsv.getRoom().getRoomtype().getId());
						Subres.setReservationTitle(rsv.getReservationStatus().getTitle());
						Subres.setSellRoom(rsv.getSellRoom());
						Subres.setDescription(rsv.getNote());
						Subres.setAdult(rsv.getAdult());
						Subres.setChild(rsv.getChild());
						// set date res in group
						Subres.setDate(rsv.getDate());
						Subres.setDateTo(rsv.getDateTo());
						Subres.setSpan(rsv.getSpan());
						Subres.setOrder(rsv.getOrder());
						Subres.setColor(rsv.getReservationStatus().getColor());
						if(dateCheckout!=null&&!dateCheckout.equals("")){
								sublist.add(Subres);
						}else{
							sublist.add(Subres);
						}
					}
					res.setTotaltax(sumAmountCharegeGroup);
					sumAmountCharegeGroup = 0.0;
					res.setSubList(sublist);
					if(nowDate.format(nowDate1).equals(nowDate.format(r.getDate()))){// CHECK ADD DATA "DATE NOW ONLY"
						if(dateCheckout!=null&&!dateCheckout.equals("")){ // Use Calendar "input date check out"
								if(TypePage=="AllGroup"||TypePage == "CheckInPendingGroup"||TypePage == "CheckOutPendingGroup"||TypePage == "TempGroup"
										||TypePage == "GuestNameGroup"	|| TypePage == "CancelResvGroup" || TypePage == "NoShowGroup" || TypePage == "DepositsGroup" 
												|| TypePage == "PaymentTrackerGroup"){
									if(!r.getGroupIdString().equals("0")&&!r.getGroupIdString().equals("")){
										list.add(res);
									}
								}else if(TypePage=="AllSingle"||TypePage == "CheckInPendingSingle"||TypePage == "CheckOutPendingSingle"||TypePage == "TempSingle"
										||TypePage == "GuestNameSingle" || TypePage == "CancelResvSingle" || TypePage == "NoShowSingle"  || TypePage == "DepositsSingle" 
										|| TypePage == "PaymentTrackerSingle"){
									if(r.getGroupIdString().equals("0")||r.getGroupIdString().equals("")){
										list.add(res);
									}
								}else{
									list.add(res);
								}
						}else{
							if(TypePage=="AllGroup"||TypePage == "CheckInPendingGroup"||TypePage == "CheckOutPendingGroup"||TypePage == "TempGroup"
									||TypePage == "GuestNameGroup" || TypePage == "CancelResvGroup" || TypePage == "NoShowGroup" || TypePage == "DepositsGroup" 
									|| TypePage == "PaymentTrackerGroup"){
								if(!r.getGroupIdString().equals("0")&&!r.getGroupIdString().equals("")){
									list.add(res);
								}
							}else if(TypePage=="AllSingle"||TypePage == "CheckInPendingSingle"||TypePage == "CheckOutPendingSingle"||TypePage == "TempSingle"
									||TypePage == "GuestNameSingle"	|| TypePage == "CancelResvSingle" || TypePage == "NoShowSingle" || TypePage == "DepositsSingle" 	
									|| TypePage == "PaymentTrackerSingle"){
								if(r.getGroupIdString().equals("0")||r.getGroupIdString().equals("")){
									list.add(res);
								}
							}else{
								if(TypePage=="CancelResv"||TypePage=="NoShow"||TypePage=="All"
										||TypePage=="CancelResvCount"||TypePage=="NoShowCount"||TypePage=="AllCount"){
									if(TypePage=="CancelResvCount"||TypePage=="NoShowCount"||TypePage=="AllCount"){
										if(nowDate.format(nowDate1).equals(nowDate.format(r.getDate()))){
											list.add(res);
										}
									}else{
										if(nowDate.format(nowDate1).equals(nowDate.format(r.getDate()))){
											list.add(res);
										}
									}
								}else{
									list.add(res);
								}
							}
						}
					}else if(TypePage == "GuestName"||TypePage == "GuestNameSingle"||TypePage == "GuestNameGroup"|| 
							TypePage == "CancelResvGroup"|| TypePage == "CancelResv"|| TypePage == "CancelResvSingle"||TypePage == "Temp"||TypePage == "TempSingle"
							||TypePage == "TempGroup" || TypePage == "NoShow"  || TypePage == "NoShowSingle"  || TypePage == "NoShowGroup"|| TypePage == "DepositsGroup" 
							|| TypePage == "DepositsSingle" || TypePage == "Deposits"|| TypePage == "PaymentTracker"|| TypePage == "PaymentTrackerGroup"|| TypePage == "PaymentTrackerSingle"
							|| TypePage == "All"||TypePage == "AllSingle"||TypePage == "AllGroup"||TypePage == "CheckInPending"||TypePage == "CheckInPendingSingle"||TypePage == "CheckInPendingGroup"
							|| TypePage == "GuestNameCount" || TypePage == "CancelResvCount" ||TypePage == "TempCount" || TypePage == "NoShowCount"
							|| TypePage == "DepositsCount" || TypePage == "PaymentTrackerCount" || TypePage == "AllCount" ||TypePage == "CheckInPendingCount"){
						if(dateCheckout!=null&&!dateCheckout.equals("")){
								if(TypePage == "GuestNameGroup"|| TypePage == "CancelResvGroup"||TypePage == "TempGroup"|| TypePage == "NoShowGroup" || TypePage == "DepositsGroup"  
								|| TypePage == "PaymentTrackerGroup"||TypePage == "AllGroup"||TypePage == "CheckInPendingGroup"){
									if(!r.getGroupIdString().equals("0")&&!r.getGroupIdString().equals("")){
										list.add(res);
									}
								}else if(TypePage == "GuestNameSingle"|| TypePage == "CancelResvSingle"||TypePage == "TempSingle" || TypePage == "NoShowSingle" || TypePage == "DepositsSingle"
									|| TypePage == "PaymentTrackerSingle"||TypePage == "AllSingle"||TypePage == "CheckInPendingSingle"){
									if(r.getGroupIdString().equals("0")||r.getGroupIdString().equals("")){
										list.add(res);
									}
								}else{
									list.add(res);
								}
						}else{
							if(TypePage == "GuestNameGroup"|| TypePage == "CancelResvGroup" ||TypePage == "TempGroup"|| TypePage == "NoShowGroup"|| TypePage == "DepositsGroup"
									|| TypePage == "PaymentTrackerGroup"||TypePage == "AllGroup"||TypePage == "CheckInPendingGroup"){
								if(!r.getGroupIdString().equals("0")&&!r.getGroupIdString().equals("")){
									list.add(res);
								}
							}else if(TypePage == "GuestNameSingle"|| TypePage == "CancelResvSingle" ||TypePage == "TempSingle"|| TypePage == "NoShowSingle"|| TypePage == "DepositsSingle"
									|| TypePage == "PaymentTrackerSingle"||TypePage == "AllSingle"||TypePage == "CheckInPendingSingel"){
								if(r.getGroupIdString().equals("0")||r.getGroupIdString().equals("")){
									list.add(res);
								}
							}else{
								if(TypePage=="CancelResv"||TypePage=="NoShow"||TypePage=="All"||TypePage == "CheckInPending"
										||TypePage=="CancelResvCount"||TypePage=="NoShowCount"||TypePage=="AllCount"||TypePage == "CheckInPendingCount"){
									if(TypePage=="CancelResvCount"||TypePage=="NoShowCount"||TypePage=="AllCount"||TypePage == "CheckInPendingCount"){
										if(nowDate.format(nowDate1).equals(nowDate.format(r.getDate()))){
											list.add(res);
										}
									}else{
										if(nowDate.format(nowDate1).equals(nowDate.format(r.getDate()))){
											list.add(res);
										}
									}
								}else{
									list.add(res);
								}
							}
						}
					}
					CheckGroup = r.getGroupIdString();
				}
			}else{
				res.setTypePage(TypePage);
				res.setDisplayId(r.getDisplayId());
				res.setId(r.getId());
				String[] ListArrayCharge = r.getChargeListString().split(",");
			    String chargeAmount;
			    String chargeAmountTemp;
			    //set status Room
			    if(!r.getRoom().getCleaningStatusString().equals("")){
			    	 res.setCleaningStatus(r.getRoom().getCleaningStatus().getTitle());
			    }
				// set charge
				for(int i = 0;i<ListArrayCharge.length;i++){
					Charge Ct = chargeLogic.GetCharge(Long.parseLong(ListArrayCharge[i]));
					if(Ct.isTemp()==false)
						sumAmountCharge += (Ct.getChargeAmount()+Ct.getTax());
					if(Ct.isRoomCharge()==false)
						sumAmountCharge += (Ct.getChargeAmount()+Ct.getTax());
					sumAmount += Ct.getChargeAmount();
				}
				if(r.getOtherChargeString()!=null&&!r.getOtherChargeString().equals("")){
					for(int k = 0;k<r.getOtherChargeList().size();k++){
						Charge OCt = r.getOtherChargeList().get(k);
						sumAmountCharge += (OCt.getChargeAmount()+OCt.getTax());
					}
				}
				chargeAmountTemp = String.valueOf(sumAmountCharge);
				res.setDefaultCherge(sumAmount);
				chargeAmount = String.valueOf(sumAmount+(taxLogic.CalTax(hotelId,sumAmount)));
				res.setChargeCheckTemp(chargeAmountTemp);
				res.setAfterNightChargeRoom(sumAmountCharge);
				
				if(r.getOtherChargeString()!=null&&!r.getOtherChargeString().equals("")){
					String reasonCancelString = "";
					for(int k = 0;k<r.getOtherChargeList().size();k++){
						Charge OCt = r.getOtherChargeList().get(k);
						sumAmountCharge += (OCt.getChargeAmount()+OCt.getTax());
						if(OCt.getReasondetailId()!=0){
							ReasonDetail reasonC = new ReasonDetailLogic().GetReasonDetail(OCt.getReasondetailId());
							reasonCancelString = reasonC.getReasonString();
						}
					}
					res.setReasoncancelString(reasonCancelString);
				}
				// set payment
				PaymentLogic paymentLogic = new PaymentLogic(req,resp);
				String[] ListArrayPaymentList = r.getPaymentListString().split(",");
				if(!ListArrayPaymentList[0].equals("")){
					for(int i = 0;i<ListArrayPaymentList.length;i++){
						if(!ListArrayPaymentList[i].equals("")){
							Payment P = paymentLogic.GetPayment(Long.parseLong(ListArrayPaymentList[i]));
							sumAmountPayment += P.getAmount();
						}
					}
				}
				res.setTax(taxLogic.CalTax(hotelId,sumAmount));
				res.setTotaltax(sumAmount+(taxLogic.CalTax(hotelId,sumAmount)));
				res.setBalance(sumAmount+(taxLogic.CalTax(hotelId,sumAmount))-sumAmountPayment);
				res.setPracketPrice(r.getPackageByDate().get(0).getPackages().getName());
				res.setPracketPriceId(r.getPackageByDate().get(0).getPackages().getId());
				res.setAfterNightChargeRoom(sumAmountCharge-sumAmountPayment);
				res.setPaymentAmount(sumAmountPayment);
				res.setPaymentList(chargeAmount);
				if(TypePage == "DepositsCount"){
				    if(sumAmountPayment<=0){continue;}
				}
				sumAmount = 0.0;
				sumAmountPayment = 0.0;
				sumAmountCharge = 0.0;
				 // set customer
                if (r.getSourcesString() != null) {
                    SourcesBusiness S = new SourcesBusinessLogic().GetSourcesBusiness(Long.parseLong(r.getSourcesString()));
                    res.setSourcesString(S.getTitle());
                }
                if (!r.getGuestString().equals("0")) {
                	String name = r.getGuest().getFirstName();
					String resId =String.valueOf(r.getId());
					if(SearchAll_checkoutPage!=null&&!SearchAll_checkoutPage.equals("")){
						if(SearchAll_checkoutPage.equals(name)){
							checkFilter = "true";
						}
						if(SearchAll_checkoutPage.equals(resId)){
							checkFilter = "true";
						}
						if(!checkFilter.equals("true")){
							checkFilter = "";
							continue;
						}
					}
                    res.setName(r.getGuest().getFirstName() + " " + r.getGuest().getLastName());
                    res.setGuestId(r.getGuest().getId());
                    res.setPhone(r.getGuest().getPhone());
                    res.setEmail(r.getGuest().getMail());
                }
				// set room
				res.setAssign(r.isAssign());
				res.setRoomName(r.getRoom().getRoomName());
				res.setRoomTypeName(r.getRoom().getRoomtype().getShortName());
				res.setRoomNameId(r.getRoom().getId());
				res.setRoomTypeId(r.getRoom().getRoomtype().getId());
				res.setSellRoom(r.getSellRoom());
				res.setOrder(r.getOrder());
				res.setDescription(r.getNote());
				res.setAdult(r.getAdult());
				res.setChild(r.getChild());
				// set date
				res.setDate(r.getDate());
				res.setDateTo(r.getDateTo());
				res.setColor(r.getReservationStatus().getColor());
				res.setReservationTitle(r.getReservationStatus().getTitle());
				res.setSpan(r.getSpan());
				
				if(nowDate.format(nowDate1).equals(nowDate.format(r.getDate()))){// CHECK ADD DATA "DATE NOW ONLY"
					if(dateCheckout!=null&&!dateCheckout.equals("")){ // Use Calendar "input date check out"
							if(TypePage=="AllGroup"||TypePage == "CheckInPendingGroup"||TypePage == "CheckOutPendingGroup"||TypePage == "TempGroup"
									||TypePage == "GuestNameGroup"	|| TypePage == "CancelResvGroup" || TypePage == "NoShowGroup" || TypePage == "DepositsGroup" 
											|| TypePage == "PaymentTrackerGroup"){
								if(!r.getGroupIdString().equals("0")&&!r.getGroupIdString().equals("")){
									list.add(res);
								}
							}else if(TypePage=="AllSingle"||TypePage == "CheckInPendingSingle"||TypePage == "CheckOutPendingSingle"||TypePage == "TempSingle"
									||TypePage == "GuestNameSingle" || TypePage == "CancelResvSingle" || TypePage == "NoShowSingle"  || TypePage == "DepositsSingle" 
									|| TypePage == "PaymentTrackerSingle"){
								if(r.getGroupIdString().equals("0")||r.getGroupIdString().equals("")){
									list.add(res);
								}
							}else{
								list.add(res);
							}
					}else{
						if(TypePage=="AllGroup"||TypePage == "CheckInPendingGroup"||TypePage == "CheckOutPendingGroup"||TypePage == "TempGroup"
								||TypePage == "GuestNameGroup" || TypePage == "CancelResvGroup" || TypePage == "NoShowGroup" || TypePage == "DepositsGroup" 
								|| TypePage == "PaymentTrackerGroup"){
							if(!r.getGroupIdString().equals("0")&&!r.getGroupIdString().equals("")){
								list.add(res);
							}
						}else if(TypePage=="AllSingle"||TypePage == "CheckInPendingSingle"||TypePage == "CheckOutPendingSingle"||TypePage == "TempSingle"
								||TypePage == "GuestNameSingle"	|| TypePage == "CancelResvSingle" || TypePage == "NoShowSingle" || TypePage == "DepositsSingle" 	
								|| TypePage == "PaymentTrackerSingle"){
							if(r.getGroupIdString().equals("0")||r.getGroupIdString().equals("")){
								list.add(res);
							}
						}else{
							if(TypePage=="CancelResv"||TypePage=="NoShow"||TypePage=="All"
									||TypePage=="CancelResvCount"||TypePage=="NoShowCount"||TypePage=="AllCount"){
								if(TypePage=="CancelResvCount"||TypePage=="NoShowCount"||TypePage=="AllCount"){
									if(nowDate.format(nowDate1).equals(nowDate.format(r.getDate()))){
										list.add(res);
									}
								}else{
									if(nowDate.format(nowDate1).equals(nowDate.format(r.getDate()))){
										list.add(res);
									}
								}
							}else{
								list.add(res);
							}
						}
					}
				}else if(TypePage == "GuestName"||TypePage == "GuestNameSingle"||TypePage == "GuestNameGroup"|| 
						TypePage == "CancelResvGroup"|| TypePage == "CancelResv"|| TypePage == "CancelResvSingle"||TypePage == "Temp"||TypePage == "TempSingle"
						||TypePage == "TempGroup" || TypePage == "NoShow"  || TypePage == "NoShowSingle"  || TypePage == "NoShowGroup"|| TypePage == "DepositsGroup" 
						|| TypePage == "DepositsSingle" || TypePage == "Deposits"|| TypePage == "PaymentTracker"|| TypePage == "PaymentTrackerGroup"|| TypePage == "PaymentTrackerSingle"
						|| TypePage == "All"||TypePage == "AllSingle"||TypePage == "AllGroup"||TypePage == "CheckInPending"||TypePage == "CheckInPendingSingle"||TypePage == "CheckInPendingGroup"
						|| TypePage == "GuestNameCount" || TypePage == "CancelResvCount" ||TypePage == "TempCount" || TypePage == "NoShowCount"
						|| TypePage == "DepositsCount" || TypePage == "PaymentTrackerCount" || TypePage == "AllCount" ||TypePage == "CheckInPendingCount"){
					if(dateCheckout!=null&&!dateCheckout.equals("")){
							if(TypePage == "GuestNameGroup"|| TypePage == "CancelResvGroup"||TypePage == "TempGroup"|| TypePage == "NoShowGroup" || TypePage == "DepositsGroup"  
							|| TypePage == "PaymentTrackerGroup"||TypePage == "AllGroup"||TypePage == "CheckInPendingGroup"){
								if(!r.getGroupIdString().equals("0")&&!r.getGroupIdString().equals("")){
									list.add(res);
								}
							}else if(TypePage == "GuestNameSingle"|| TypePage == "CancelResvSingle"||TypePage == "TempSingle" || TypePage == "NoShowSingle" || TypePage == "DepositsSingle"
								|| TypePage == "PaymentTrackerSingle"||TypePage == "AllSingle"||TypePage == "CheckInPendingSingle"){
								if(r.getGroupIdString().equals("0")||r.getGroupIdString().equals("")){
									list.add(res);
								}
							}else{
								list.add(res);
							}
					}else{
						if(TypePage == "GuestNameGroup"|| TypePage == "CancelResvGroup" ||TypePage == "TempGroup"|| TypePage == "NoShowGroup"|| TypePage == "DepositsGroup"
								|| TypePage == "PaymentTrackerGroup"||TypePage == "AllGroup"||TypePage == "CheckInPendingGroup"){
							if(!r.getGroupIdString().equals("0")&&!r.getGroupIdString().equals("")){
								list.add(res);
							}
						}else if(TypePage == "GuestNameSingle"|| TypePage == "CancelResvSingle" ||TypePage == "TempSingle"|| TypePage == "NoShowSingle"|| TypePage == "DepositsSingle"
								|| TypePage == "PaymentTrackerSingle"||TypePage == "AllSingle"||TypePage == "CheckInPendingSingel"){
							if(r.getGroupIdString().equals("0")||r.getGroupIdString().equals("")){
								list.add(res);
							}
						}else{
							if(TypePage=="CancelResv"||TypePage=="NoShow"||TypePage=="All"||TypePage == "CheckInPending"
									||TypePage=="CancelResvCount"||TypePage=="NoShowCount"||TypePage=="AllCount"||TypePage == "CheckInPendingCount"){
								if(TypePage=="CancelResvCount"||TypePage=="NoShowCount"||TypePage=="AllCount"||TypePage == "CheckInPendingCount"){
									if(nowDate.format(nowDate1).equals(nowDate.format(r.getDate()))){
										list.add(res);
									}
								}else{
									if(nowDate.format(nowDate1).equals(nowDate.format(r.getDate()))){
										list.add(res);
									}
								}
							}else{
								list.add(res);
							}
						}
					}
				}
			}
		}
		return list;
	}

public List < ReservationDataForReport > GetReservationAllReportPage(long hotelId, String TypePage, String dateCheckin,
		String dateCheckout, String typeReservation, long line, long pointer,String SearchAll_checkoutPage)
		throws ParseException {
		    List < ReservationDataForReport > list = new ArrayList < ReservationDataForReport > ();
		    Double sumAmount = 0.0;
		    Double sumAmountPayment = 0.0;
		    Double sumAmountCharge = 0.0;
		    Double sumAmountCharegeGroup = 0.0;
		    Double paymentGroup = 0.0;
		    int checkSizeSubList = 0;
			int checkGroupSubList = 0;
		    List < Reservation > resvList;
		    List < Reservation > resvListCheckDate = new ArrayList < Reservation >();
		    if (TypePage == "CheckIn") {
		        resvList = GetReservation_Report(hotelId, "CheckIn", "", "", "");
		    } else if (TypePage == "CheckInPending" || TypePage == "CheckInPendingSingle" || TypePage == "CheckInPendingGroup") {
		        if (TypePage == "CheckInPendingSingle") {
		            resvList = GetReservation_Report(hotelId, "CheckInPendingSingle", dateCheckin, dateCheckout, "");
		        } else if (TypePage == "CheckInPendingGroup") {
		            resvList = GetReservation_Report(hotelId, "CheckInPendingGroup", dateCheckin, dateCheckout, "");
		        } else {
		            resvList = GetReservation_Report(hotelId, "CheckInPending", dateCheckin, dateCheckout, "");
		        }
		    } else if (TypePage == "Deposits" || TypePage == "DepositsSingle" || TypePage == "DepositsGroup") {
		        if (TypePage == "DepositsSingle") {
		            resvList = GetReservation_Report(hotelId, "DepositsSingle", dateCheckin, dateCheckout, "");
		        } else if (TypePage == "DepositsGroup") {
		            resvList = GetReservation_Report(hotelId, "DepositsGroup", dateCheckin, dateCheckout, "");
		        } else {
		            resvList = GetReservation_Report(hotelId, "Deposits", dateCheckin, dateCheckout, "");
		        }
		    } else if (TypePage == "Temp" || TypePage == "TempSingle" || TypePage == "TempGroup") {
		        if (TypePage == "TempGroup") {
		            resvList = GetReservation_Report(hotelId, "TempGroup", dateCheckin, dateCheckout, "");
		        } else if (TypePage == "TempSingle") {
		            resvList = GetReservation_Report(hotelId, "TempSingle", dateCheckin, dateCheckout, "");
		        } else {
		            resvList = GetReservation_Report(hotelId, "Temp", dateCheckin, dateCheckout, "");
		        }
		    } else if (TypePage == "CancelResv" || TypePage == "CancelResvSingle" || TypePage == "CancelResvGroup") {
		        if (TypePage == "CancelResvSingle") {
		            resvList = GetReservation_Report(hotelId, "CancelResvSingle", dateCheckin, dateCheckout, "");
		        } else if (TypePage == "CancelResvGroup") {
		            resvList = GetReservation_Report(hotelId, "CancelResvGroup", dateCheckin, dateCheckout, "");
		        } else {
		            resvList = GetReservation_Report(hotelId, "CancelResv", dateCheckin, dateCheckout, "");
		        }
		    } else if (TypePage == "NoShow" || TypePage == "NoShowSingle" || TypePage == "NoShowGroup") {
		        if (TypePage == "NoShowSingle") {
		            resvList = GetReservation_Report(hotelId, "NoShowSingle", dateCheckin, dateCheckout, "");
		        } else if (TypePage == "NoShowGroup") {
		            resvList = GetReservation_Report(hotelId, "NoShowGroup", dateCheckin, dateCheckout, "");
		        } else {
		            resvList = GetReservation_Report(hotelId, "NoShow", dateCheckin, dateCheckout, "");
		        }
		    } else if (TypePage == "CheckOutPending" || TypePage == "CheckOutPendingSingle" || TypePage == "CheckOutPendingGroup") {
		        if (TypePage == "CheckOutPendingSingle") {
		            resvList = GetReservation_Report(hotelId, "CheckOutPendingSingle", "", "", "");
		        } else if (TypePage == "CheckOutPendingGroup") {
		            resvList = GetReservation_Report(hotelId, "CheckOutPendingGroup", "", "", "");
		        } else {
		            resvList = GetReservation_Report(hotelId, "CheckOutPending", "", "", "");
		        }
		    } else if (TypePage == "PaymentTracker" || TypePage == "PaymentTrackerSingle" || TypePage == "PaymentTrackerGroup") {
		        if (TypePage == "PaymentTrackerSingle") {
		            resvList = GetReservation_Report(hotelId, "PaymentTrackerSingle", dateCheckin, dateCheckout, "");
		        } else if (TypePage == "PaymentTrackerGroup") {
		            resvList = GetReservation_Report(hotelId, "PaymentTrackerGroup", dateCheckin, dateCheckout, "");
		        } else {
		            resvList = GetReservation_Report(hotelId, "PaymentTracker", dateCheckin, dateCheckout, "");
		        }
		    } else if (TypePage == "GuestName" || TypePage == "GuestNameSingle" || TypePage == "GuestNameGroup") {
		        if (TypePage == "GuestNameSingle") {
		            resvList = GetReservation_Report(hotelId, "GuestNameSingle", dateCheckin, dateCheckout, typeReservation);
		        } else if (TypePage == "GuestNameGroup") {
		            resvList = GetReservation_Report(hotelId, "GuestNameGroup", dateCheckin, dateCheckout, typeReservation);
		        } else {
		            resvList = GetReservation_Report(hotelId, "GuestName", dateCheckin, dateCheckout, typeReservation);
		        }
		    } else if (TypePage == "All" || TypePage == "AllSingle" || TypePage == "AllGroup") {
		        if (TypePage == "AllSingle") {
		            resvList = GetReservation_Report(hotelId, "AllSingle", dateCheckin, dateCheckout, typeReservation);
		        } else if (TypePage == "AllGroup") {
		            resvList = GetReservation_Report(hotelId, "AllGroup", dateCheckin, dateCheckout, typeReservation);
		        } else {
		            resvList = GetReservation_Report(hotelId, "All", dateCheckin, dateCheckout, typeReservation);
		        }
		    } else {
		        resvList = GetReservation_Report(hotelId, "CheckIn", "", "", "");
		    }
		    Date nowDate1 = new GenericLogic(req,resp).ServerDateTime(hotelId);
		    SimpleDateFormat nowDate = new SimpleDateFormat("yyyyMMdd");
		    SimpleDateFormat nowDateCheckDate = new SimpleDateFormat("yyyy-MM-dd");
		    String CheckGroup = "";	
		    String CheckGroupDouble = "";
		    TaxLogic taxLogic = new TaxLogic(req,resp);
		    ChargeLogic chargeLogic = new ChargeLogic(req,resp);
		    if(dateCheckin!=null){
			    for(Reservation r: resvList){
		    		Date dCheckin = nowDateCheckDate.parse(dateCheckin);
		    		Date dCheckout = nowDateCheckDate.parse(dateCheckout);
			    	if(r.getDateTo().after(dCheckin)||r.getDateTo().equals(dCheckin)){
			    		if(dCheckin.after(r.getDate())||(r.getDate().before(dCheckout)||r.getDate().equals(dCheckout)))
			    			resvListCheckDate.add(r);
			    	}
			    }  
			    resvList = resvListCheckDate;
		    }
		    for (Reservation r: resvList) {
		    	String checkFilter = "";
		        if (list.size() < (line * pointer)) {
		            List < ReservationDataForReport > sublist = new ArrayList < ReservationDataForReport > ();
		            ReservationDataForReport res = new ReservationDataForReport();
		            if (r.getGroupIdNumber() != 0) {
		            	checkGroupSubList = 0;
		                if (!CheckGroup.equals(r.getGroupIdString())) {
		                	if(list.size()!=0){
		                		for(int l =0;l<list.size();l++){
			                		if(list.get(l).getGroupId()==r.getGroupIdNumber()){
			                			CheckGroupDouble = "1";
			                		}
			                	}
		                	}
		                	if(CheckGroupDouble=="1"){
		                		CheckGroupDouble = "";
		                		continue;
		                	}
		                    res.setTypePage(TypePage);
		                    res.setReservationTitle(r.getReservationStatus().getTitle());
		                    //set Agency group
		                    if (r.getAgencyIdString() != null && !r.getAgencyIdString().equals("0")) {
		                        Agency obj = new AgencyLogic(req,resp).GetAgency(Long.parseLong(r.getAgencyIdString()));
		                        res.setAgencyString(obj.getAgency());
		                    }
		                    //set customer group
		                    String[] splitResId = r.getGroupId().getListResvString().split(",");
							for(int i =0;i<splitResId.length;i++){
								if(SearchAll_checkoutPage!=null)
									if(SearchAll_checkoutPage.equals(splitResId[i].trim()))
										checkFilter = "true";
							}
		                    if (r.getGroupId().getGuest() != null) {
		                    	String name = r.getGroupId().getGuest().getFirstName();
								String groupId =String.valueOf(r.getGroupId().getId());
								if(SearchAll_checkoutPage!=null&&!SearchAll_checkoutPage.equals("")){
									String firstStringSearch = SearchAll_checkoutPage.substring(0,1);
									if(firstStringSearch.equals("G")||firstStringSearch.equals("g"))
										SearchAll_checkoutPage = SearchAll_checkoutPage.substring(1,SearchAll_checkoutPage.length());
									if(SearchAll_checkoutPage.equals(name)){
										checkFilter = "true";
									}
									if(SearchAll_checkoutPage.equals(groupId)){
										checkFilter = "true";
									}
									if(!checkFilter.equals("true"))
										continue;
								}
		                        res.setName(r.getGroupId().getGuest().getFirstName() + " " + r.getGroupId().getGuest().getLastName());
		                        res.setGuestId(r.getGroupId().getGuest().getId());
		                        res.setPhone(r.getGroupId().getGuest().getPhone());
		                        res.setEmail(r.getGroupId().getGuest().getMail());
		                    } else {
		                        res.setName("");
		                    }
		                    //set payment group
							PaymentLogic paymentLogic = new PaymentLogic(req,resp);
		                    String[] ListPaymentGroup = r.getGroupId().getPaymentListString().split(",");
		                    if (!ListPaymentGroup[0].equals("")) {
		                        for (int p = 0; p < ListPaymentGroup.length; p++) {
		                            long paymentIdStirng = Long.parseLong(ListPaymentGroup[p]);
		                            Payment paymentData = paymentLogic.GetPayment(paymentIdStirng);
		                            paymentGroup += paymentData.getAmount();
		                        }
		                    }
		                    res.setPaymentAmount(paymentGroup);
		                    if(TypePage == "Deposits" || TypePage == "DepositsSingle" || TypePage == "DepositsGroup"){
		                    	if(paymentGroup<=0){continue;}
		                    }
		                    //setCharge group
		                    String chargeAmountTempGroup = "";
		                    String[] ListArrayChargeGroup = r.getChargeListString().split(",");
		                    for (int cg = 0; cg < ListArrayChargeGroup.length; cg++) {
		                        Charge Ct = chargeLogic.GetCharge(Long.parseLong(ListArrayChargeGroup[cg]));
		                        if (Ct != null) {
		                            if (Ct.isTemp() == false)
		                                sumAmountCharge += (Ct.getChargeAmount() + Ct.getTax());
		                            if (Ct.isRoomCharge() == false)
		                                sumAmountCharge += (Ct.getChargeAmount() + Ct.getTax());
		                        }
		                    }
		                    if (r.getGroupId().getOtherChargeString() != null && !r.getGroupId().getOtherChargeString().equals("")) {
		                        for (int k = 0; k < r.getGroupId().getOtherChargeList().size(); k++) {
		                            Charge OCt = r.getGroupId().getOtherChargeList().get(k);
		                            sumAmountCharge += (OCt.getChargeAmount() + OCt.getTax());
		                        }
		                    }
		                    chargeAmountTempGroup = String.valueOf(sumAmountCharge);
		                    res.setChargeCheckTemp(chargeAmountTempGroup);
		                    if (sumAmountCharge > 0) {
		                        res.setAfterNightChargeRoom(sumAmountCharge - paymentGroup);
		                    } else {
		                        res.setAfterNightChargeRoom(sumAmountCharge);
		                    }
		              
		                    sumAmountCharge = 0.0;
		                    //set Group group
		                    res.setGroupIdString(r.getGroupIdString());
		                    res.setGroupId(r.getGroupIdNumber());
		                    res.setId(r.getId());
		                    res.setDisplayId(r.getDisplayId());
		                    res.setDescription(r.getGroupId().getNote());
		                    res.setResLis(r.getGroupId().getListResvString());
		                    //set Room group
		                    res.setAssign(r.isAssign());
		                    res.setRoomName(r.getRoom().getRoomName());
		                    res.setRoomTypeName(r.getRoom().getRoomtype().getShortName());
		                    res.setRoomNameId(r.getRoom().getId());
		                    res.setRoomTypeId(r.getRoom().getRoomtype().getId());
		                    //set Date group
		                    res.setDate(r.getDate());
		                    res.setDateTo(r.getDateTo());
		                    res.setOrder(r.getOrder());
		                    res.setSellRoom(r.getSellRoom());
		                    res.setColor(r.getReservationStatus().getColor());
		                    res.setSpan(r.getGroupId().getSpan());
		                    // reservation in group
		                    String[] ArrayResvList = r.getGroupId().getListResvString().split(",");
		                    for (int i = 0; i < ArrayResvList.length; i++) {
		                        ReservationDataForReport Subres = new ReservationDataForReport();
		                        Reservation rsv = GetReservation(Long.parseLong(ArrayResvList[i].trim()));
		                        Subres.setGroupId(rsv.getGroupIdNumber());
		                        Subres.setId(rsv.getId());
		                        Subres.setDisplayId(rsv.getDisplayId());
		                        //set status Room
		                        Subres.setCleaningStatus(rsv.getRoom().getCleaningStatus().getTitle());
		                        //set reason
		                        String[] ListArrayCharge = rsv.getChargeListString().split(",");
		                        String[] ListArrayPaymentList = rsv.getPaymentListString().split(",");
		                        String chargeAmount;
		                        String chargeAmountTemp;
		                        //set charge res in group
		                        for (int j = 0; j < ListArrayCharge.length; j++) {
		                            Charge Ct = chargeLogic.GetCharge(Long.parseLong(ListArrayCharge[j]));
		                            if (Ct != null) {
		                                if (Ct.isTemp() == false)
		                                    sumAmountCharge += (Ct.getChargeAmount() + Ct.getTax());
		                                if (Ct.isRoomCharge() == false)
		                                    sumAmountCharge += (Ct.getChargeAmount() + Ct.getTax());
		                            }
		                            if (Ct != null)
		                                sumAmount += Ct.getChargeAmount();
		                        }
		                        if (rsv.getOtherChargeString() != null && !rsv.getOtherChargeString().equals("")) {
		                            String reasonCancelString = "";
		                            for (int k = 0; k < rsv.getOtherChargeList().size(); k++) {
		                                Charge OCt = rsv.getOtherChargeList().get(k);
		                                sumAmountCharge += (OCt.getChargeAmount() + OCt.getTax());
		                                if (OCt.getReasondetailId() != 0) {
		                                    ReasonDetail reasonC = new ReasonDetailLogic().GetReasonDetail(OCt.getReasondetailId());
		                                    reasonCancelString = reasonC.getReasonString();
		                                }
		                            }
		                            Subres.setReasoncancelString(reasonCancelString);
		                        }
		                        sumAmountCharegeGroup += sumAmount + (taxLogic.CalTax(hotelId, sumAmount));
		                        chargeAmountTemp = String.valueOf(sumAmountCharge);
		                        chargeAmount = String.valueOf(sumAmount + (taxLogic.CalTax(hotelId, sumAmount)));
		                        Subres.setDefaultCherge(sumAmount);
		                        Subres.setChargeCheckTemp(chargeAmountTemp);
		                        Subres.setPaymentList(chargeAmount);
		                        Subres.setAfterNightChargeRoom(sumAmountCharge);
		                        //set payment res in group
		                        if (!ListArrayPaymentList[0].equals("")) {
		                            for (int j = 0; j < ListArrayPaymentList.length; j++) {
		                                String paymentIdString = String.valueOf(ListArrayPaymentList[j]);
		                                if (!paymentIdString.equals("")) {
		                                    Payment P = paymentLogic.GetPayment(Long.parseLong(paymentIdString));
		                                    sumAmountPayment += P.getAmount();
		                                }
		                            }
		                        }
		                        Subres.setTax(taxLogic.CalTax(hotelId, sumAmount));
		                        Subres.setTotaltax(sumAmount + (taxLogic.CalTax(hotelId, sumAmount)));
		                        Subres.setBalance(sumAmount + (taxLogic.CalTax(hotelId, sumAmount)) - sumAmountPayment);
		                        Subres.setPracketPrice(rsv.getPackageByDate().get(0).getPackages().getName());
		                        Subres.setPaymentAmount(sumAmountPayment);
		                        sumAmountPayment = 0.0;
		                        sumAmount = 0.0;
		                        sumAmountCharge = 0.0;
		                        // set customer res in group
		                        if (rsv.getSourcesString() != null) {
		                            SourcesBusiness S = new SourcesBusinessLogic().GetSourcesBusiness(Long.parseLong(rsv.getSourcesString()));
		                            Subres.setSourcesString(S.getTitle());
		                        }
		                        if (rsv.getAgencyIdString() != null && !rsv.getAgencyIdString().equals("0")) {
		                            Agency obj = new AgencyLogic(req,resp).GetAgency(Long.parseLong(rsv.getAgencyIdString()));
		                            Subres.setAgencyString(obj.getAgency());
		                        }
		                        if (!rsv.getGuestString().equals("0")) {
		                            Subres.setName(rsv.getGuest().getFirstName() + " " + rsv.getGuest().getLastName());
		                            Subres.setGuestId(rsv.getGuest().getId());
		                            Subres.setPhone(rsv.getGuest().getPhone());
		                            Subres.setEmail(rsv.getGuest().getMail());
		                        }
		                        // set room res in group
		                        Subres.setAssign(rsv.isAssign());
		                        Subres.setRoomName(rsv.getRoom().getRoomName());
		                        Subres.setRoomTypeName(rsv.getRoom().getRoomtype().getShortName());
		                        Subres.setRoomNameId(rsv.getRoom().getId());
		                        Subres.setRoomTypeId(rsv.getRoom().getRoomtype().getId());
		                        Subres.setReservationTitle(rsv.getReservationStatus().getTitle());
		                        Subres.setSellRoom(rsv.getSellRoom());
		                        Subres.setDescription(rsv.getNote());
		                        Subres.setAdult(rsv.getAdult());
		                        Subres.setChild(rsv.getChild());
		                        // set date res in group
		                        Subres.setDate(rsv.getDate());
		                        Subres.setDateTo(rsv.getDateTo());
		                        Subres.setSpan(rsv.getSpan());
		                        Subres.setOrder(rsv.getOrder());
		                        Subres.setColor(rsv.getReservationStatus().getColor());
		                        if(((line*pointer)-checkSizeSubList)>0){
	                        		sublist.add(Subres);
									checkGroupSubList = 1;
									checkSizeSubList++;
								}
		                    }
		                    res.setTotaltax(sumAmountCharegeGroup);
		                    sumAmountCharegeGroup = 0.0;
		                    res.setSubList(sublist);
		                    if (nowDate.format(nowDate1).equals(nowDate.format(r.getDate()))) { // CHECK ADD DATA "DATE NOW ONLY"
		                        if (dateCheckout != null && !dateCheckout.equals("")) { // Use Calendar "input date check out"
		                        	if (TypePage == "AllGroup" || TypePage == "CheckInPendingGroup"  || TypePage == "TempGroup" || TypePage == "GuestNameGroup" || TypePage == "CancelResvGroup" || TypePage == "NoShowGroup" || TypePage == "DepositsGroup" || TypePage == "PaymentTrackerGroup") {
		                            	if(TypePage == "AllGroup" ||TypePage == "CheckOutPendingGroup" ||TypePage == "NoShowGroup" ||TypePage == "CancelResvGroup"
		                            			||TypePage == "TempGroup"){
		                            		if(!r.getGroupIdString().equals("0")||!r.getGroupIdString().equals("")){
												if(checkGroupSubList==0){
													continue;
												}
												list.add(res);
											}else{
												checkSizeSubList=0;
											}
		                            	}else{
		                            		if (!r.getGroupIdString().equals("0") && !r.getGroupIdString().equals("")) {
			                                    list.add(res);
			                                }
		                            	}
		                            } else if (TypePage == "AllSingle"  || TypePage == "CheckOutPendingSingle" || TypePage == "TempSingle" || TypePage == "GuestNameSingle" || TypePage == "CancelResvSingle" || TypePage == "NoShowSingle" || TypePage == "DepositsSingle" || TypePage == "PaymentTrackerSingle") {
		                                if (r.getGroupIdString().equals("0") || r.getGroupIdString().equals("")) {
		                                	if(TypePage == "AllSingle" || TypePage == "CheckInPendingSingle" || TypePage == "TempSingle"){
		                                		if(checkGroupSubList==0){
		    										continue;
		    									}
		    									list.add(res);
		                                	}else{
		                                		list.add(res);
		                                	}
		                                }else{
											checkSizeSubList=0;
										}
		                            } else {
		                            	if(TypePage=="All"||TypePage=="CheckInPending" || TypePage == "NoShow" ||TypePage == "CancelResv" || TypePage == "Temp" 
		                            			|| TypePage == "CheckOutPending" || TypePage == "Deposits" || TypePage == "GuestName"){
	    									if(checkGroupSubList==0){
	    										continue;
	    									}
	    									list.add(res);
		    							} else {
		                                    list.add(res);
		    							}
		                            }
		                        } else {
		                            if (TypePage == "AllGroup" || TypePage == "CheckInPendingGroup" || TypePage == "CheckOutPendingGroup" 
		                            		|| TypePage == "TempGroup" || TypePage == "GuestNameGroup" || TypePage == "CancelResvGroup" 
		                            		|| TypePage == "NoShowGroup" || TypePage == "DepositsGroup" || TypePage == "PaymentTrackerGroup") {
	                            		if(!r.getGroupIdString().equals("0")||!r.getGroupIdString().equals("")){
											if(checkGroupSubList==0){
												continue;
											}
											list.add(res);
										}else{
											checkSizeSubList=0;
										}
		                            } else if (TypePage == "AllSingle"  || TypePage == "CheckOutPendingSingle" || TypePage == "TempSingle" 
		                            		|| TypePage == "GuestNameSingle" || TypePage == "CancelResvSingle" || TypePage == "NoShowSingle" 
		                            		|| TypePage == "DepositsSingle" || TypePage == "PaymentTrackerSingle") {
		                                if (r.getGroupIdString().equals("0") || r.getGroupIdString().equals("")) {
		                                	if(TypePage == "AllSingle" || TypePage == "CheckInPendingSingle"){
			                                	if(nowDate.format(nowDate1).equals(nowDate.format(r.getDate()))){
			    									if(checkGroupSubList==0){
			    										continue;
			    									}
			    									list.add(res);
			    								}else{
			    									checkSizeSubList=0;
			    								}
			                                }else {
			                                    list.add(res);
			                                }
		                                }else{
		                                	checkSizeSubList = 0;
		                                }
		                            } else {
		                                if(TypePage == "All"||TypePage=="CheckInPending" || TypePage == "NoShow" ||TypePage == "CancelResv" 
		                                		|| TypePage == "CheckOutPending"){
		                                	if(nowDate.format(nowDate1).equals(nowDate.format(r.getDate()))){
		    									if(checkGroupSubList==0){
		    										continue;
		    									}
		    									list.add(res);
		    								}else{
		    									checkSizeSubList=0;
		    								}
		                                }else {
		                                	if(TypePage == "Temp" || TypePage == "Deposits" || TypePage == "PaymentTracker"){
		                                		if(nowDate.format(nowDate1).equals(nowDate.format(r.getDate()))){
			    									if(checkGroupSubList==0){
			    										continue;
			    									}
			    									list.add(res);
			    								}else{
			    									checkSizeSubList=0;
			    								}
		                                	}else{
		                                		list.add(res);
		                                	}
		                                }
		                            }
		                        }
		                    } else if (TypePage == "GuestName" || TypePage == "GuestNameSingle" || TypePage == "GuestNameGroup" ||
		                        TypePage == "CancelResvGroup" || TypePage == "CancelResv" || TypePage == "CancelResvSingle" 
		                        || TypePage == "Temp" || TypePage == "TempSingle" || TypePage == "TempGroup" || TypePage == "NoShow" 
		                        || TypePage == "NoShowSingle" || TypePage == "NoShowGroup" || TypePage == "DepositsGroup" 
		                        || TypePage == "DepositsSingle" || TypePage == "Deposits" || TypePage == "PaymentTracker" 
		                        || TypePage == "PaymentTrackerGroup" || TypePage == "PaymentTrackerSingle" || TypePage == "All" 
		                        || TypePage == "AllSingle" || TypePage == "AllGroup" || TypePage == "CheckInPending" 
		                        || TypePage == "CheckInPendingSingle" || TypePage == "CheckInPendingGroup"
		                        || TypePage == "CheckOutPending") {
		                        if (dateCheckout != null && !dateCheckout.equals("")) {
		                            if (TypePage == "GuestNameGroup" || TypePage == "CancelResvGroup" || TypePage == "TempGroup" || TypePage == "NoShowGroup" || TypePage == "DepositsGroup" || TypePage == "PaymentTrackerGroup" || TypePage == "AllGroup" ) {
		                            	if(TypePage == "AllGroup" || TypePage == "CheckInPendingGroup" || TypePage == "NoShowGroup" || TypePage == "CancelResvGroup"
		                            			||TypePage == "TempGroup"||TypePage =="DepositsGroup" || TypePage == "PaymentTrackerGroup" 
		                            			|| TypePage == "GuestNameGroup"){
		                            		if(!r.getGroupIdString().equals("0")||!r.getGroupIdString().equals("")){
												if(checkGroupSubList==0){
													continue;
												}
												list.add(res);
											}else{
												checkSizeSubList=0;
											}
		                            	}else{
		                            		if (!r.getGroupIdString().equals("0") && !r.getGroupIdString().equals("")) {
			                                    list.add(res);
			                                }
		                            	}
		                            } else if (TypePage == "GuestNameSingle" || TypePage == "CancelResvSingle" || TypePage == "TempSingle" 
		                            		|| TypePage == "NoShowSingle" || TypePage == "DepositsSingle" || TypePage == "PaymentTrackerSingle" 
		                            		|| TypePage == "AllSingle" || TypePage == "CheckInPendingSingle") {
		                                if (r.getGroupIdString().equals("0") || r.getGroupIdString().equals("")) {
		                                	if(TypePage=="AllSingle" || TypePage == "CheckInPendingSingle" || TypePage == "PaymentTrackerSingle"
		                                			||TypePage == "GuestNameSingle"){
		    									if(checkGroupSubList==0){
		    										continue;
		    									}
		    									list.add(res);
			    							} else {
			                                    list.add(res);
			    							}
		                                }else{
		                                	checkSizeSubList = 0;
		                                }
		                            } else {
		                            	if(TypePage=="All"||TypePage=="CheckInPending" || TypePage == "NoShow" ||TypePage == "CancelResv" || TypePage == "Temp" 
		                            			|| TypePage == "CheckOutPending" || TypePage == "Deposits"){
	    									if(checkGroupSubList==0){
	    										continue;
	    									}
	    									list.add(res);
		    							} else {
		                                    list.add(res);
		    							}
		                            }
		                        } else {
		                            if (TypePage == "GuestNameGroup" || TypePage == "CancelResvGroup" || TypePage == "TempGroup" || TypePage == "NoShowGroup" || TypePage == "DepositsGroup" || TypePage == "PaymentTrackerGroup" || TypePage == "AllGroup" || TypePage == "CheckInPendingGroup") {
		                              //  if (!r.getGroupIdString().equals("0") && !r.getGroupIdString().equals("")) {
		                               //     list.add(res);
		                               // }
		                            	 if (!r.getGroupIdString().equals("0") || !r.getGroupIdString().equals("")) {
		    									if(checkGroupSubList==0){
		    										continue;
		    									}
		    									list.add(res);
			                                }else{
			                                	checkSizeSubList = 0;
			                                }
		                            } else if (TypePage == "GuestNameSingle" || TypePage == "CancelResvSingle" || TypePage == "TempSingle" || TypePage == "NoShowSingle" || TypePage == "DepositsSingle" || TypePage == "PaymentTrackerSingle" || TypePage == "AllSingle") {
		                                if (r.getGroupIdString().equals("0") || r.getGroupIdString().equals("")) {
		                                	if(TypePage=="AllSingle" || TypePage == "CheckInPendingSingel" || TypePage == "PaymentTrackerSingle"){
			    								if(nowDate.format(nowDate1).equals(nowDate.format(r.getDate()))){
			    									if(checkGroupSubList==0){
			    										continue;
			    									}
			    									list.add(res);
			    								}else{
			    									checkSizeSubList=0;
			    								}
			    							} else {
			                                    list.add(res);
			                                }
		                                }else{
		                                	checkSizeSubList = 0;
		                                }
		                            } else {
		                                if(TypePage=="All"||TypePage=="CheckInPending" || TypePage == "NoShow" || TypePage == "CancelResv" 
		                                		|| TypePage == "CheckOutPending"){
		    								if(nowDate.format(nowDate1).equals(nowDate.format(r.getDate()))){
		    									if(checkGroupSubList==0){
		    										continue;
		    									}
		    									list.add(res);
		    								}else{
		    									checkSizeSubList=0;
		    								}
		    							} else {
		    								if(TypePage == "Temp" || TypePage == "Deposits" || TypePage == "PaymentTracker" || TypePage == "GuestName"){
		    									if(checkGroupSubList==0){
		    										continue;
		    									}
		    									list.add(res);
		    								}else{
		    									list.add(res);
		    								}
		                                    
		                                }
		                            }
		                        }
		                    }
		                    CheckGroup = r.getGroupIdString();
		                }
		            } else {
		                res.setTypePage(TypePage);
		                res.setId(r.getId());
		                res.setDisplayId(r.getDisplayId());
		                String[] ListArrayCharge = r.getChargeListString().split(",");
		                String chargeAmount;
		                String chargeAmountTemp;
		                //set status Room
		                if (!r.getRoom().getCleaningStatusString().equals("")) {
		                    res.setCleaningStatus(r.getRoom().getCleaningStatus().getTitle());
		                }
		                // set charge
		                for (int i = 0; i < ListArrayCharge.length; i++) {
		                    Charge Ct = chargeLogic.GetCharge(Long.parseLong(ListArrayCharge[i]));
		                    if (Ct.isTemp() == false)
		                        sumAmountCharge += (Ct.getChargeAmount() + Ct.getTax());
		                    if (Ct.isRoomCharge() == false)
		                        sumAmountCharge += (Ct.getChargeAmount() + Ct.getTax());
		                    sumAmount += Ct.getChargeAmount();
		                }
		                if (r.getOtherChargeString() != null && !r.getOtherChargeString().equals("")) {
		                    for (int k = 0; k < r.getOtherChargeList().size(); k++) {
		                        Charge OCt = r.getOtherChargeList().get(k);
		                        sumAmountCharge += (OCt.getChargeAmount() + OCt.getTax());
		                    }
		                }
		                chargeAmountTemp = String.valueOf(sumAmountCharge);
		                res.setDefaultCherge(sumAmount);
		                chargeAmount = String.valueOf(sumAmount + (taxLogic.CalTax(hotelId, sumAmount)));
		                res.setChargeCheckTemp(chargeAmountTemp);
		                res.setAfterNightChargeRoom(sumAmountCharge);
		                
		                if(r.getOtherChargeString()!=null&&!r.getOtherChargeString().equals("")){
							String reasonCancelString = "";
							for(int k = 0;k<r.getOtherChargeList().size();k++){
								Charge OCt = r.getOtherChargeList().get(k);
								sumAmountCharge += (OCt.getChargeAmount()+OCt.getTax());
								if(OCt.getReasondetailId()!=0){
									ReasonDetail reasonC = new ReasonDetailLogic().GetReasonDetail(OCt.getReasondetailId());
									reasonCancelString = reasonC.getReasonString();
								}
							}
							res.setReasoncancelString(reasonCancelString);
						}
		                // set payment
						PaymentLogic paymentLogic = new PaymentLogic(req,resp);
		                String[] ListArrayPaymentList = r.getPaymentListString().split(",");
		                if (!ListArrayPaymentList[0].equals("")) {
		                    for (int i = 0; i < ListArrayPaymentList.length; i++) {
		                        if (!ListArrayPaymentList[i].equals("")) {
		                            Payment P = paymentLogic.GetPayment(Long.parseLong(ListArrayPaymentList[i]));
		                            sumAmountPayment += P.getAmount();
		                        }
		                    }
		                }
		                res.setTax(taxLogic.CalTax(hotelId, sumAmount));
		                res.setTotaltax(sumAmount + (taxLogic.CalTax(hotelId, sumAmount)));
		                res.setBalance(sumAmount + (taxLogic.CalTax(hotelId, sumAmount)) - sumAmountPayment);
		                res.setPracketPrice(r.getPackageByDate().get(0).getPackages().getName());
		                res.setPracketPriceId(r.getPackageByDate().get(0).getPackages().getId());
		                res.setAfterNightChargeRoom(sumAmountCharge - sumAmountPayment);
		                res.setPaymentAmount(sumAmountPayment);
		                res.setPaymentList(chargeAmount);
		                if(TypePage == "Deposits" || TypePage == "DepositsSingle" || TypePage == "DepositsGroup"){
	                    	if(sumAmountPayment<=0){continue;}
	                    }
		                sumAmount = 0.0;
		                sumAmountPayment = 0.0;
		                sumAmountCharge = 0.0;
		                // set customer
		                if (r.getSourcesString() != null) {
		                    SourcesBusiness S = new SourcesBusinessLogic().GetSourcesBusiness(Long.parseLong(r.getSourcesString()));
		                    res.setSourcesString(S.getTitle());
		                }
		                if (!r.getGuestString().equals("0")) {
		                	String name = r.getGuest().getFirstName();
							String resId =String.valueOf(r.getId());
							if(SearchAll_checkoutPage!=null&&!SearchAll_checkoutPage.equals("")){
								if(SearchAll_checkoutPage.equals(name)){
									checkFilter = "true";
								}
								if(SearchAll_checkoutPage.equals(resId)){
									checkFilter = "true";
								}
								if(!checkFilter.equals("true")){
									checkFilter = "";
									continue;
								}
							}
		                    res.setName(r.getGuest().getFirstName() + " " + r.getGuest().getLastName());
		                    res.setGuestId(r.getGuest().getId());
		                    res.setPhone(r.getGuest().getPhone());
		                    res.setEmail(r.getGuest().getMail());
		                }
		                // set room
		                res.setAssign(r.isAssign());
		                res.setRoomName(r.getRoom().getRoomName());
		                res.setRoomTypeName(r.getRoom().getRoomtype().getShortName());
		                res.setRoomNameId(r.getRoom().getId());
		                res.setRoomTypeId(r.getRoom().getRoomtype().getId());
		                res.setSellRoom(r.getSellRoom());
		                res.setOrder(r.getOrder());
		                res.setDescription(r.getNote());
		                res.setAdult(r.getAdult());
		                res.setChild(r.getChild());
		                // set date
		                res.setDate(r.getDate());
		                res.setDateTo(r.getDateTo());
		                res.setColor(r.getReservationStatus().getColor());
		                res.setReservationTitle(r.getReservationStatus().getTitle());
		                res.setSpan(r.getSpan());
		
		                if (nowDate.format(nowDate1).equals(nowDate.format(r.getDate()))) { // CHECK ADD DATA "DATE NOW ONLY"
		                    if (dateCheckout != null && !dateCheckout.equals("")) { // Use Calendar "input date check out"
		                        if (TypePage == "AllGroup" || TypePage == "CheckInPendingGroup" || TypePage == "CheckOutPendingGroup" || TypePage == "TempGroup" || TypePage == "GuestNameGroup" || TypePage == "CancelResvGroup" || TypePage == "NoShowGroup" || TypePage == "DepositsGroup" || TypePage == "PaymentTrackerGroup") {
		                            if (!r.getGroupIdString().equals("0") && !r.getGroupIdString().equals("")) {
		                                list.add(res);
		                            }
		                        } else if (TypePage == "AllSingle"  || TypePage == "CheckOutPendingSingle" || TypePage == "TempSingle" || TypePage == "GuestNameSingle" || TypePage == "CancelResvSingle" || TypePage == "NoShowSingle" || TypePage == "DepositsSingle" || TypePage == "PaymentTrackerSingle") {
		                            if (r.getGroupIdString().equals("0") || r.getGroupIdString().equals("")) {
		                            	if(TypePage == "AllSingle" || TypePage == "CheckInPendingSingle"|| TypePage == "NoShowSingle"
		                            	|| TypePage == "TempSingle"){
			                            	if(((line*pointer)-checkSizeSubList)>0){
			    								list.add(res);
			    								checkSizeSubList++;
			    							}
			                            }else {
			                                list.add(res);
			                            }
		                            }
		                        } else {
		                        	if(TypePage == "All"||TypePage=="CheckInPending" || TypePage == "NoShow" ||TypePage == "CancelResv" || TypePage == "Temp" 
		                        			|| TypePage == "CheckOutPending" || TypePage == "Deposits" || TypePage == "PaymentTracker"
		                        			|| TypePage == "GuestName"){
		                            	if(((line*pointer)-checkSizeSubList)>0){
		    								list.add(res);
		    								checkSizeSubList++;
		    							}
		                            }else {
		                                list.add(res);
		                            }
		                        }
		                    } else {
		                        if (TypePage == "AllGroup" || TypePage == "CheckInPendingGroup" || TypePage == "CheckOutPendingGroup" || TypePage == "TempGroup" || TypePage == "GuestNameGroup" || TypePage == "CancelResvGroup" || TypePage == "NoShowGroup" || TypePage == "DepositsGroup" || TypePage == "PaymentTrackerGroup") {
		                            if (!r.getGroupIdString().equals("0") && !r.getGroupIdString().equals("")) {
		                                list.add(res);
		                            }
		                        } else if (TypePage == "AllSingle" || TypePage == "CheckOutPendingSingle" || TypePage == "TempSingle" || TypePage == "GuestNameSingle" || TypePage == "CancelResvSingle" || TypePage == "NoShowSingle" || TypePage == "DepositsSingle" || TypePage == "PaymentTrackerSingle") {
		                            if (r.getGroupIdString().equals("0") || r.getGroupIdString().equals("")) {
		                            	if(TypePage == "AllSingle" || TypePage == "CheckInPendingSingle" || TypePage == "CheckOutPendingSingle" || TypePage == "PaymentTrackerSingle"){
			                            	if(((line*pointer)-checkSizeSubList)>0){
			    								list.add(res);
			    								checkSizeSubList++;
			    							}
			                            }else {
			                                list.add(res);
			                            }
		                            }
		                        } else {
		                           if(TypePage == "All"||TypePage=="CheckInPending" || TypePage == "NoShow" ||TypePage == "CancelResv" || TypePage == "Temp" 
		                        		   || TypePage == "CheckOutPending" || TypePage == "Deposits" || TypePage == "PaymentTracker"
		                        		   || TypePage == "GuestName"){
		                            	if(((line*pointer)-checkSizeSubList)>0){
		    								list.add(res);
		    								checkSizeSubList++;
		    							}
		                            }else {
		                                list.add(res);
		                            }
		                        }
		                    }
		                } else if (TypePage == "GuestName" || TypePage == "GuestNameSingle" || TypePage == "GuestNameGroup" ||
		                    TypePage == "CancelResvGroup" || TypePage == "CancelResv" || TypePage == "CancelResvSingle" || TypePage == "Temp" 
		                    || TypePage == "TempSingle" || TypePage == "TempGroup" || TypePage == "NoShow" || TypePage == "NoShowSingle" 
		                    || TypePage == "NoShowGroup" || TypePage == "DepositsGroup" || TypePage == "DepositsSingle" 
		                    || TypePage == "Deposits" || TypePage == "PaymentTracker" || TypePage == "PaymentTrackerGroup" 
		                    || TypePage == "PaymentTrackerSingle" || TypePage == "All" || TypePage == "AllSingle" || TypePage == "AllGroup" 
		                    || TypePage == "CheckInPending" || TypePage == "CheckInPendingSingle" || TypePage == "CheckInPendingGroup"
		                    || TypePage == "CheckOutPending") {
		                    if (dateCheckout != null && !dateCheckout.equals("")) {
		                        if (TypePage == "GuestNameGroup" || TypePage == "CancelResvGroup" || TypePage == "TempGroup" || TypePage == "NoShowGroup" || TypePage == "DepositsGroup" || TypePage == "PaymentTrackerGroup" || TypePage == "AllGroup" || TypePage == "CheckInPendingGroup") {
		                        	if(!r.getGroupIdString().equals("0")||!r.getGroupIdString().equals("")){
										if(checkGroupSubList==0){
											continue;
										}
										list.add(res);
									}else{
										checkSizeSubList=0;
									}
		                        	//if (!r.getGroupIdString().equals("0") && !r.getGroupIdString().equals("")) {
		                            //    list.add(res);
		                            //}
		                        } else if (TypePage == "GuestNameSingle" || TypePage == "CancelResvSingle" || TypePage == "TempSingle" 
		                        		|| TypePage == "NoShowSingle" || TypePage == "DepositsSingle" || TypePage == "PaymentTrackerSingle" 
		                        		|| TypePage == "AllSingle"|| TypePage == "CheckInPendingSingle") {
		                            if (r.getGroupIdString().equals("0") || r.getGroupIdString().equals("")) {
		                            	if(TypePage == "AllSingle" || TypePage == "CheckInPendingSingle" || TypePage == "NoShowSingle"
		                            			|| TypePage == "DepositsSingle" || TypePage == "PaymentTrackerSingle"
		                            			|| TypePage == "GuestNameSingle"){
			                            	if(((line*pointer)-checkSizeSubList)>0){
			    								list.add(res);
			    								checkSizeSubList++;
			    							}
			                            }else {
			                                list.add(res);
			                            }
		                            }
		                        } else {
		                        	if(TypePage == "All"||TypePage=="CheckInPending" || TypePage == "NoShow" || TypePage == "CancelResv" || TypePage == "Temp" 
		                        			|| TypePage == "CheckOutPending" || TypePage == "Deposits" || TypePage == "PaymentTracker"){
		                            	if(((line*pointer)-checkSizeSubList)>0){
		    								list.add(res);
		    								checkSizeSubList++;
		    							}
		                            }else {
		                                list.add(res);
		                            }
		                        }
		                    } else {
		                        if (TypePage == "GuestNameGroup" || TypePage == "CancelResvGroup" || TypePage == "TempGroup" || TypePage == "NoShowGroup" || TypePage == "DepositsGroup" || TypePage == "PaymentTrackerGroup" || TypePage == "AllGroup" || TypePage == "CheckInPendingGroup") {
		                            if (!r.getGroupIdString().equals("0") && !r.getGroupIdString().equals("")) {
		                                list.add(res);
		                            }
		                        } else if (TypePage == "GuestNameSingle" || TypePage == "CancelResvSingle" || TypePage == "TempSingle" || TypePage == "NoShowSingle" || TypePage == "DepositsSingle" || TypePage == "PaymentTrackerSingle" || TypePage == "AllSingle") {
		                            if (r.getGroupIdString().equals("0") || r.getGroupIdString().equals("")) {
		                            	if(TypePage == "AllSingle" || TypePage == "CheckInPendingSingel"){
		                            		if (nowDate.format(nowDate1).equals(nowDate.format(r.getDate()))) {
				                            	if(((line*pointer)-checkSizeSubList)>0){
				    								list.add(res);
				    								checkSizeSubList++;
				    							}
		                            		}
			                            }else {
			                                list.add(res);
			                            }
		                            }
		                        } else {
	                            	if(TypePage == "All"||TypePage=="CheckInPending" || TypePage == "NoShow" || TypePage == "CancelResv" 
	                            			|| TypePage == "CheckOutPending"){
	                            		if (nowDate.format(nowDate1).equals(nowDate.format(r.getDate()))) {
			                            	if(((line*pointer)-checkSizeSubList)>0){
			    								list.add(res);
			    								checkSizeSubList++;
			    							}
	                            		}
		                            }else {
		                            	if(TypePage == "Temp"|| TypePage == "Deposits" || TypePage == "PaymentTracker" || TypePage == "GuestName"){
			                            	if(((line*pointer)-checkSizeSubList)>0){
			    								list.add(res);
			    								checkSizeSubList++;
			    							}
		                            	}else{
		                            		list.add(res);
		                            	}
		                            }
		                        }
		                    }
		                }
		            }
		        }
		    }
		    List<ReservationDataForReport> listForReturn = new ArrayList<ReservationDataForReport>();
			long countSizeAll = 0;
			long countSetToReturn = ((pointer-1)*line);
			long checkGroup = 0;
			long checkLine = 0;
			for(int i = 0;i<list.size();i++){
				long checkAddGroup = 0;
				if(list.get(i).subList!=null){ // use for group between page
					if(pointer>1){
						checkAddGroup = list.get(i).subList.size()+(countSizeAll-(pointer-1)*line);
					}else{
						checkAddGroup = list.get(i).subList.size()+countSizeAll;
					}
					if(checkAddGroup<=line&&countSizeAll>=countSetToReturn){
						if(checkLine<line){
							listForReturn.add(list.get(i));
							checkLine++;
						}
					}else{
						if(checkGroup==0){
							for(int j=0;j<list.get(i).subList.size();j++){
								countSizeAll++;
								if(countSizeAll>countSetToReturn){
									if(checkLine<line){
										listForReturn.add(list.get(i).subList.get(j));
										checkLine++;
									}
								}
							}
							if(listForReturn.size()>0){
								checkGroup = 1;
							}
						}else{
							if(checkLine<line){
								listForReturn.add(list.get(i));
								checkLine++;
							}
						}
					}
				}else{
					if(countSizeAll>=countSetToReturn){
						listForReturn.add(list.get(i));
					}
					countSizeAll++;
				}
			}
			return listForReturn;
		}


	public List<ReservationDataForReport> GetReservationAllReportRoomManage(long hotelId,long groupId)
			throws ParseException {
		List<ReservationDataForReport> list = new ArrayList<ReservationDataForReport>();
		Double sumAmount = 0.0;
		Double sumAmountPayment = 0.0;
		Double sumAmountCharge = 0.0;
		List<Reservation> resvList;
		resvList = GetReservationInGroup(groupId);
		String CheckGroup = "";
		TaxLogic taxLogic = new TaxLogic(req,resp);
		ChargeLogic chargeLogic = new ChargeLogic(req,resp);
		for (Reservation r : resvList) {
		List<ReservationDataForReport> sublist = new ArrayList<ReservationDataForReport>();
		ReservationDataForReport res = new ReservationDataForReport();
			if(r.getGroupIdNumber()!=0){
				if(!CheckGroup.equals(r.getGroupIdString())){
					res.setDescription(r.getGroupId().getNote());
					res.setResLis(r.getGroupId().getListResvString());
					res.setGroupIdString(r.getGroupIdString());
					res.setGroupId(r.getGroupIdNumber());
					res.setId(r.getId());
					if(r.getGroupId().getGuest() != null)	
					{
						res.setName(r.getGroupId().getGuest().getFirstName() +" "+r.getGroupId().getGuest().getLastName());
						res.setGuestId(r.getGroupId().getGuest().getId());
						res.setPhone(r.getGroupId().getGuest().getPhone());
					}else{
						res.setName("");
					}
					res.setAssign(r.isAssign());
					res.setRoomName(r.getRoom().getRoomName());
					res.setRoomTypeName(r.getRoom().getRoomtype().getShortName());
					res.setRoomNameId(r.getRoom().getId());
					res.setRoomTypeId(r.getRoom().getRoomtype().getId());
					res.setDate(r.getDate());
					res.setDateTo(r.getDateTo());
					res.setOrder(r.getOrder());
					res.setColor(r.getReservationStatus().getColor());
					res.setReservationTitle(r.getReservationStatus().getTitle());
					res.setSellRoom(r.getSellRoom());
					res.setPaymentAmount(0.0);
					res.setSpan(r.getGroupId().getSpan());
					String[] ArrayResvList = r.getGroupId().getListResvString().split(",");
					for(int i = 0;i<ArrayResvList.length;i++){
						ReservationDataForReport Subres = new ReservationDataForReport();
						Reservation rsv = GetReservation(Long.parseLong(ArrayResvList[i].trim()));
						String[] ListArrayCharge = rsv.getChargeListString().split(",");
						String[] ListArrayPaymentList = rsv.getPaymentListString().split(",");
					    String chargeAmount;
					    String chargeAmountTemp;
					  //set status Room
					    Subres.setCleaningStatus(rsv.getRoom().getCleaningStatus().getTitle());
						for(int j = 0;j<ListArrayCharge.length;j++){
							Charge C = chargeLogic.GetCharge(Long.parseLong(ListArrayCharge[j]));
							sumAmount += C.getChargeAmount();
							if(C.isTemp()==false){
								sumAmountCharge += (C.getChargeAmount()+C.getTax());
							}
						}
						PaymentLogic paymentLogic = new PaymentLogic(req,resp);
						if(!ListArrayPaymentList[0].equals("")){
							for(int j = 0;j<ListArrayPaymentList.length;j++){
								String paymentIdString = String.valueOf(ListArrayPaymentList[j]);
								if(!paymentIdString.equals("")){
									Payment P = paymentLogic.GetPayment(Long.parseLong(paymentIdString));
									sumAmountPayment += P.getAmount();
								}
							}
						}
						chargeAmountTemp = String.valueOf(sumAmountCharge);
						chargeAmount = String.valueOf(sumAmount+(taxLogic.CalTax(hotelId,sumAmount)));
						
						Subres.setGroupId(rsv.getGroupIdNumber());
						Subres.setDefaultCherge(sumAmount);
						Subres.setTax(taxLogic.CalTax(hotelId,sumAmount));
						Subres.setTotaltax(sumAmount+(taxLogic.CalTax(hotelId,sumAmount)));
						Subres.setBalance(sumAmount+(taxLogic.CalTax(hotelId,sumAmount))-sumAmountPayment);
						Subres.setPracketPrice(rsv.getPackageByDate().get(0).getPackages().getName());
						
						sumAmount = 0.0;
						sumAmountPayment = 0.0;
						sumAmountCharge = 0.0;
						if(rsv.getSourcesString()!=null){
							SourcesBusiness S = new SourcesBusinessLogic().GetSourcesBusiness(Long.parseLong(rsv.getSourcesString()));
							Subres.setSourcesString(S.getTitle());
						}
						Subres.setChargeCheckTemp(chargeAmountTemp);
						Subres.setPaymentAmount(sumAmountPayment);
						Subres.setDescription(rsv.getNote());
						Subres.setPaymentList(chargeAmount);
						Subres.setAdult(rsv.getAdult());
						Subres.setChild(rsv.getChild());
						Subres.setId(rsv.getId());
						if(!rsv.getGuestString().equals("0")){
							Subres.setName(rsv.getGuest().getFirstName() +" "+ rsv.getGuest().getLastName());
							Subres.setPhone(rsv.getGuest().getPhone());
						}
						Subres.setAssign(rsv.isAssign());
						Subres.setRoomName(rsv.getRoom().getRoomName());
						Subres.setRoomTypeName(rsv.getRoom().getRoomtype().getShortName());
						Subres.setRoomNameId(rsv.getRoom().getId());
						Subres.setRoomTypeId(rsv.getRoom().getRoomtype().getId());
						Subres.setDate(rsv.getDate());
						Subres.setDateTo(rsv.getDateTo());
						Subres.setOrder(rsv.getOrder());
						Subres.setColor(rsv.getReservationStatus().getColor());
						Subres.setReservationTitle(rsv.getReservationStatus().getTitle());
						Subres.setSellRoom(rsv.getSellRoom());
						Subres.setSpan(rsv.getSpan());
						sublist.add(Subres);
					}
					res.setSubList(sublist);
					list.add(res);
					CheckGroup = r.getGroupIdString();
				}
			}else{
				String[] ListArrayCharge = r.getChargeListString().split(",");
				String[] ListArrayPaymentList = r.getPaymentListString().split(",");
			    String chargeAmount;
			    String chargeAmountTemp;
			    //set status Room
			    res.setCleaningStatus(r.getRoom().getCleaningStatus().getTitle());
				for(int i = 0;i<ListArrayCharge.length;i++){
					Charge C = chargeLogic.GetCharge(Long.parseLong(ListArrayCharge[i]));
					sumAmount += C.getChargeAmount();
					if(C.isTemp()==false){
						sumAmountCharge += (C.getChargeAmount()+C.getTax());
					}
				}
				PaymentLogic paymentLogic = new PaymentLogic(req,resp);
				if(!ListArrayPaymentList[0].equals("")){
					for(int i = 0;i<ListArrayPaymentList.length;i++){
						if(!ListArrayPaymentList[i].equals("")){
							Payment P = paymentLogic.GetPayment(Long.parseLong(ListArrayPaymentList[i]));
							sumAmountPayment += P.getAmount();
						}
					}
				}
				chargeAmountTemp = String.valueOf(sumAmountCharge);
				chargeAmount = String.valueOf(sumAmount+(taxLogic.CalTax(hotelId,sumAmount)));
				
				res.setPhone(r.getGuest().getPhone());
				res.setDefaultCherge(sumAmount);
				res.setTax(taxLogic.CalTax(hotelId,sumAmount));
				res.setTotaltax(sumAmount+(taxLogic.CalTax(hotelId,sumAmount)));
				res.setBalance(sumAmount+(taxLogic.CalTax(hotelId,sumAmount))-sumAmountPayment);
				res.setPracketPrice(r.getPackageByDate().get(0).getPackages().getName());
				
				sumAmount = 0.0;
				sumAmountPayment = 0.0;
				sumAmountCharge = 0.0;
				if(r.getSourcesString()!=null){
					SourcesBusiness S = new SourcesBusinessLogic().GetSourcesBusiness(Long.parseLong(r.getSourcesString()));
					res.setSourcesString(S.getTitle());
				}
				res.setChargeCheckTemp(chargeAmountTemp);
				res.setPaymentAmount(sumAmountPayment);
				res.setDescription(r.getNote());
				res.setPaymentList(chargeAmount);
				res.setAdult(r.getAdult());
				res.setChild(r.getChild());
				res.setId(r.getId());
				if(!r.getGuestString().equals("0")){
					res.setName(r.getGuest().getFirstName() + " "
							+ r.getGuest().getLastName());
				}
				res.setAssign(r.isAssign());
				res.setRoomName(r.getRoom().getRoomName());
				res.setRoomTypeName(r.getRoom().getRoomtype().getShortName());
				res.setRoomNameId(r.getRoom().getId());
				res.setRoomTypeId(r.getRoom().getRoomtype().getId());
				res.setDate(r.getDate());
				res.setOrder(r.getOrder());
				res.setColor(r.getReservationStatus().getColor());
				res.setReservationTitle(r.getReservationStatus().getTitle());
				res.setSellRoom(r.getSellRoom());
				res.setSpan(r.getSpan());
				list.add(res);
			}
		}
		return list;
	}
	
	public ReservationDataForReport GetReservationRoomManage(long hotelId,long resId)
			throws ParseException {
		Double sumAmount = 0.0;
		Double sumAmountPayment = 0.0;
		Double sumAmountCharge = 0.0;
		Reservation r = GetReservation(resId);
		ReservationDataForReport res = new ReservationDataForReport();
		res.setId(r.getId());
		String[] ListArrayCharge = r.getChargeListString().split(",");
		String[] ListArrayPaymentList = r.getPaymentListString().split(",");
	    String chargeAmount;
	    String chargeAmountTemp;
	    ChargeLogic chargeLogic = new ChargeLogic(req,resp);
		// set charge
		for(int i = 0;i<ListArrayCharge.length;i++){
			Charge Ct = chargeLogic.GetCharge(Long.parseLong(ListArrayCharge[i]));
			if(Ct.isTemp()==false)
				sumAmountCharge += (Ct.getChargeAmount()+Ct.getTax());
			if(Ct.isRoomCharge()==false)
				sumAmountCharge += (Ct.getChargeAmount()+Ct.getTax());
			sumAmount += Ct.getChargeAmount();
		}
		if(r.getOtherChargeString()!=null&&!r.getOtherChargeString().equals("")){
			for(int k = 0;k<r.getOtherChargeList().size();k++){
				Charge OCt = r.getOtherChargeList().get(k);
				sumAmountCharge += (OCt.getChargeAmount()+OCt.getTax());
			}
		}
		chargeAmountTemp = String.valueOf(sumAmountCharge);
		res.setDefaultCherge(sumAmount);
		chargeAmount = String.valueOf(sumAmount+(new TaxLogic(req,resp).CalTax(hotelId,sumAmount)));
		res.setChargeCheckTemp(chargeAmountTemp);
		res.setAfterNightChargeRoom(sumAmountCharge);
		
		// set payment
		PaymentLogic paymentLogic = new PaymentLogic(req,resp);
		if(!ListArrayPaymentList[0].equals("")){
			for(int i = 0;i<ListArrayPaymentList.length;i++){
				if(!ListArrayPaymentList[i].equals("")){
					Payment P = paymentLogic.GetPayment(Long.parseLong(ListArrayPaymentList[i]));
					sumAmountPayment += P.getAmount();
				}
			}
		}
		TaxLogic taxLogic = new TaxLogic(req,resp);
		res.setTax(taxLogic.CalTax(hotelId,sumAmount));
		res.setTotaltax(sumAmount+(taxLogic.CalTax(hotelId,sumAmount)));
		res.setBalance(sumAmount+(taxLogic.CalTax(hotelId,sumAmount))-sumAmountPayment);
		res.setPracketPrice(r.getPackageByDate().get(0).getPackages().getName());
		res.setAfterNightChargeRoom(sumAmountCharge-sumAmountPayment);
		res.setPaymentAmount(sumAmountPayment);
		res.setPaymentList(chargeAmount);
		sumAmount = 0.0;
		sumAmountPayment = 0.0;
		sumAmountCharge = 0.0;
		// set customer
		if(r.getSourcesString()!=null){
			SourcesBusiness S = new SourcesBusinessLogic().GetSourcesBusiness(Long.parseLong(r.getSourcesString()));
			res.setSourcesString(S.getTitle());
		}
		if(!r.getGuestString().equals("0")){
			res.setName(r.getGuest().getFirstName() + " " + r.getGuest().getLastName());
			res.setGuestId(r.getGuest().getId());
			res.setPhone(r.getGuest().getPhone());
			res.setEmail(r.getGuest().getMail());
		}
		// set room
		res.setAssign(r.isAssign());
		res.setRoomName(r.getRoom().getRoomName());
		res.setRoomTypeName(r.getRoom().getRoomtype().getShortName());
		res.setRoomNameId(r.getRoom().getId());
		res.setRoomTypeId(r.getRoom().getRoomtype().getId());
		res.setSellRoom(r.getSellRoom());
		res.setOrder(r.getOrder());
		res.setDescription(r.getNote());
		res.setAdult(r.getAdult());
		res.setChild(r.getChild());
		// set date
		res.setDate(r.getDate());
		res.setDateTo(r.getDateTo());
		res.setColor(r.getReservationStatus().getColor());
		res.setReservationTitle(r.getReservationStatus().getTitle());
		res.setSpan(r.getSpan());
		return res;
	}
	
	public List<Reservation> GetReservation(long hotelId, Date resDate,
			long span) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(resDate);
		cal.add(Calendar.DATE, (int) span);

		Query q = new Query(EntityName.Reservation);
		
		Filter filterHotel = new FilterPredicate("hotelId",
				FilterOperator.EQUAL, hotelId);
		Filter filterresDate = new FilterPredicate("dateTo",
				FilterOperator.GREATER_THAN_OR_EQUAL, resDate);
		Filter filter = CompositeFilterOperator.and(filterresDate, filterHotel);
		q.setFilter(filter);
		
		List<Reservation> list1 = GetList(datastore.prepare(q).asList(
				FetchOptions.Builder.withDefaults()));
		List<Reservation> result = new ArrayList<Reservation>();
		
		for(Reservation r : list1)
		{
			if(r.getDate().after(Util.addDays(resDate,span -1)))
				continue;
			result.add(r);
		}

		return result;
	}
	public List<Reservation> GetReservation_All(long hotelId) {
		Query q = new Query(EntityName.Reservation);
		Filter filterHotel = new FilterPredicate("hotelId",
				FilterOperator.EQUAL, hotelId);
		q.setFilter(filterHotel).addSort("date", SortDirection.DESCENDING);

		return GetList(datastore.prepare(q).asList(
				FetchOptions.Builder.withDefaults()));
	}
	public List<Reservation> GetReservation_AllCheckoutOnly(long hotelId,String TypePage,String dateCheckin,String dateCheckout) throws ParseException {
		Query q = new Query(EntityName.Reservation);
		ReservationStatus fCheckin = new GenericLogic(req,resp).GetReservationStatus(hotelId,"Checked-in Rooms");
		String statusResIdCheckin = String.valueOf(fCheckin.getId());
		ReservationStatus fCheckOut = new GenericLogic(req,resp).GetReservationStatus(hotelId,"Checked-out Rooms");
		String statusResIdCheckout = String.valueOf(fCheckOut.getId());
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
				Locale.ENGLISH);
		Filter filterHotel = new FilterPredicate("hotelId",
				FilterOperator.EQUAL, hotelId);
		Filter filterStatusCheckin = new FilterPredicate("ReservationStatus",
				FilterOperator.EQUAL, statusResIdCheckin);
		Filter filterStatusCheckout = new FilterPredicate("ReservationStatus",
				FilterOperator.EQUAL, statusResIdCheckout);
		Filter filterOr = CompositeFilterOperator.or(filterStatusCheckin,filterStatusCheckout);
		if(TypePage=="ExpressAllCount"||TypePage=="ExpressAll"||TypePage=="ExpressGroup"||TypePage=="ExpressSingle"){
			if(dateCheckin!=null&&dateCheckout!=null&&!dateCheckin.equals("")&&!dateCheckout.equals("")){
				Date dateCheckin_value = formatter.parse(dateCheckin);
				Date dateCheckout_value = formatter.parse(dateCheckout);
				
				if(!dateCheckin_value.equals("")&&!dateCheckout_value.equals("")){
					Filter filterDateCheckin = new FilterPredicate("dateTo",FilterOperator.GREATER_THAN_OR_EQUAL, dateCheckin_value);
					Filter filterDateCheckout = new FilterPredicate("dateTo",FilterOperator.LESS_THAN_OR_EQUAL, dateCheckout_value);
					Filter filterOrDate = CompositeFilterOperator.and(filterDateCheckin,filterDateCheckout);
					Filter filter = CompositeFilterOperator.and(filterHotel,filterOrDate,filterStatusCheckout);
					q.setFilter(filter).addSort("dateTo", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
				}
			}else{
				if(TypePage=="ExpressAllCount"||TypePage=="ExpressAll"||TypePage=="ExpressGroup"||TypePage=="ExpressSingle"){
					Filter filter = CompositeFilterOperator.and(filterHotel,filterStatusCheckout);
					q.setFilter(filter).addSort("dateTo", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
				}else if(TypePage=="CheckOutPending"||TypePage=="CheckOutPendingSingle"||TypePage=="CheckOutPendingGroup"||TypePage=="CheckOutPendingCount"){
					Filter filter = CompositeFilterOperator.and(filterHotel,filterStatusCheckin);
					q.setFilter(filter).addSort("dateTo", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
				}else{
					Filter filter = CompositeFilterOperator.and(filterHotel,filterOr);
					q.setFilter(filter).addSort("dateTo", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
				}
			}
		}else{
			if(dateCheckin!=null&&dateCheckout!=null&&!dateCheckin.equals("")&&!dateCheckout.equals("")){
				Date dateCheckin_value = formatter.parse(dateCheckin);
				Date dateCheckout_value = formatter.parse(dateCheckout);
				if(!dateCheckin_value.equals("")&&!dateCheckout_value.equals("")){
					Filter filterDateCheckin = new FilterPredicate("dateTo",FilterOperator.GREATER_THAN_OR_EQUAL, dateCheckin_value);
					Filter filterDateCheckout = new FilterPredicate("dateTo",FilterOperator.LESS_THAN_OR_EQUAL, dateCheckout_value);
					Filter filterOrDate = CompositeFilterOperator.and(filterDateCheckin,filterDateCheckout);
					Filter filter = CompositeFilterOperator.and(filterHotel,filterOrDate,filterOr);
					q.setFilter(filter).addSort("dateTo", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
				}
			}else{
				if(TypePage=="ExpressAllCount"||TypePage=="ExpressAll"||TypePage=="ExpressGroup"||TypePage=="ExpressSingle"){
					Filter filter = CompositeFilterOperator.and(filterHotel,filterStatusCheckout);
					q.setFilter(filter).addSort("dateTo", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
				}else if(TypePage=="CheckOutPending"||TypePage=="CheckOutPendingSingle"||TypePage=="CheckOutPendingGroup"||TypePage=="CheckOutPendingCount"){
					Filter filter = CompositeFilterOperator.and(filterHotel,filterStatusCheckin);
					q.setFilter(filter).addSort("dateTo", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
				}else{
					Filter filter = CompositeFilterOperator.and(filterHotel,filterOr);
					q.setFilter(filter).addSort("dateTo", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
				}
			}
		}
		return GetList(datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()));
	}
	
	public List<Reservation> GetReservation_AllCheckoutOnlyPage(long hotelId,String TypePage,String dateCheckin,String dateCheckout,long line,long pointer) throws ParseException {
		Query q = new Query(EntityName.Reservation);
		ReservationStatus fCheckin = new GenericLogic(req,resp).GetReservationStatus(hotelId,"Checked-in Rooms");
		String statusResIdCheckin = String.valueOf(fCheckin.getId());
		ReservationStatus fCheckOut = new GenericLogic(req,resp).GetReservationStatus(hotelId,"Checked-out Rooms");
		String statusResIdCheckout = String.valueOf(fCheckOut.getId());
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
				Locale.ENGLISH);
		Filter filterHotel = new FilterPredicate("hotelId",
				FilterOperator.EQUAL, hotelId);
		Filter filterStatusCheckin = new FilterPredicate("ReservationStatus",
				FilterOperator.EQUAL, statusResIdCheckin);
		Filter filterStatusCheckout = new FilterPredicate("ReservationStatus",
				FilterOperator.EQUAL, statusResIdCheckout);
		Filter filterOr = CompositeFilterOperator.or(filterStatusCheckin,filterStatusCheckout);
		if(TypePage=="ExpressAll"||TypePage=="ExpressGroup"||TypePage=="ExpressSingle"){
			if(dateCheckin!=null&&dateCheckout!=null&&!dateCheckin.equals("")&&!dateCheckout.equals("")){
				Date dateCheckin_value = formatter.parse(dateCheckin);
				Date dateCheckout_value = formatter.parse(dateCheckout);
				if(!dateCheckin_value.equals("")&&!dateCheckout_value.equals("")){
					Filter filterDateCheckin = new FilterPredicate("dateTo",FilterOperator.GREATER_THAN_OR_EQUAL, dateCheckin_value);
					Filter filterDateCheckout = new FilterPredicate("dateTo",FilterOperator.LESS_THAN_OR_EQUAL, dateCheckout_value);
					Filter filterOrDate = CompositeFilterOperator.and(filterDateCheckin,filterDateCheckout);
					Filter filter = CompositeFilterOperator.and(filterHotel,filterOrDate,filterStatusCheckout);
					q.setFilter(filter).addSort("dateTo", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
				}
			}else{
				Filter filter = CompositeFilterOperator.and(filterHotel,filterStatusCheckout);
				q.setFilter(filter).addSort("dateTo", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
			}
		}else{
			if(dateCheckin!=null&&dateCheckout!=null&&!dateCheckin.equals("")&&!dateCheckout.equals("")){
				Date dateCheckin_value = formatter.parse(dateCheckin);
				Date dateCheckout_value = formatter.parse(dateCheckout);
				if(!dateCheckin_value.equals("")&&!dateCheckout_value.equals("")){
					Filter filterDateCheckin = new FilterPredicate("dateTo",FilterOperator.GREATER_THAN_OR_EQUAL, dateCheckin_value);
					Filter filterDateCheckout = new FilterPredicate("dateTo",FilterOperator.LESS_THAN_OR_EQUAL, dateCheckout_value);
					Filter filterOrDate = CompositeFilterOperator.and(filterDateCheckin,filterDateCheckout);
					Filter filter = null;
					if(TypePage=="CheckOutPending"||TypePage=="CheckOutPendingSingle"||TypePage=="CheckOutPendingGroup"||TypePage=="CheckOutPendingCount"){
						filter = CompositeFilterOperator.and(filterHotel,filterOrDate,filterStatusCheckin);
					}else
						filter = CompositeFilterOperator.and(filterHotel,filterOrDate,filterOr);
					q.setFilter(filter).addSort("dateTo", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
				}
			}else if(TypePage=="CheckOutPending"||TypePage=="CheckOutPendingSingle"||TypePage=="CheckOutPendingGroup"||TypePage=="CheckOutPendingCount"){
				Filter filter = CompositeFilterOperator.and(filterHotel,filterStatusCheckin);
				q.setFilter(filter).addSort("dateTo", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
			}else{
				Filter filter = CompositeFilterOperator.and(filterHotel,filterOr);
				q.setFilter(filter).addSort("dateTo", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
			}
		}
		return GetList(datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()));
	}
	
	public List<Reservation> GetReservation_Report(long hotelId, String TypePage,String dateCheckin,String dateCheckout,String type_reservation) throws ParseException {
		Query q = new Query(EntityName.Reservation);
		String statusResIdCheckin ="";
		String	statusResIdresv = "";
		String	statusResIdcheckout = "";
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
				Locale.ENGLISH);
		GenericLogic gLogic = new GenericLogic(req,resp);
		if(TypePage=="All"||TypePage=="AllGroup"||TypePage=="AllSingle"){
			ReservationStatus fCheckin = gLogic.GetReservationStatus(hotelId,"Checked-in Rooms");
			statusResIdCheckin = String.valueOf(fCheckin.getId());
			ReservationStatus fresv = gLogic.GetReservationStatus(hotelId,"Reserved Rooms");
			statusResIdresv = String.valueOf(fresv.getId());
			ReservationStatus fCheckOut = gLogic.GetReservationStatus(hotelId,"Checked-out Rooms");
			statusResIdcheckout = String.valueOf(fCheckOut.getId());
			Filter filterHotel = new FilterPredicate("hotelId",
					FilterOperator.EQUAL, hotelId);
			Filter filterStatusCheckin = new FilterPredicate("ReservationStatus",
					FilterOperator.EQUAL, statusResIdCheckin);
			Filter filterStatusresv = new FilterPredicate("ReservationStatus",
					FilterOperator.EQUAL, statusResIdresv);
			Filter filterStatuscheckOut = new FilterPredicate("ReservationStatus",
					FilterOperator.EQUAL, statusResIdcheckout);
			Filter filterOr = CompositeFilterOperator.or(filterStatusCheckin,filterStatusresv,filterStatuscheckOut);
			Filter filter = null;
			if(dateCheckin!=null&&dateCheckout!=null&&!dateCheckin.equals("")&&!dateCheckout.equals("")){
				Date dateCheckin_value = formatter.parse(dateCheckin);
				Date dateCheckout_value = formatter.parse(dateCheckout);
				if(!dateCheckin_value.equals("")&&!dateCheckout_value.equals("")){
					Filter filterDateCheckin = new FilterPredicate("date",FilterOperator.GREATER_THAN_OR_EQUAL, dateCheckin_value);
					Filter filterDateCheckout = new FilterPredicate("date",FilterOperator.LESS_THAN_OR_EQUAL, dateCheckout_value);
					Filter filterOrDate = CompositeFilterOperator.or(filterDateCheckin,filterDateCheckout);
					if(type_reservation.equals("reservationType_A"))
						filter = CompositeFilterOperator.and(filterHotel,filterOr,filterOrDate);
					else if(type_reservation.equals("Checked-out Rooms"))
						filter = CompositeFilterOperator.and(filterHotel,filterStatuscheckOut,filterOrDate);
					else if(type_reservation.equals("Checked-in Rooms"))
						filter = CompositeFilterOperator.and(filterHotel,filterStatusCheckin,filterOrDate);
					else if(type_reservation.equals("Reserved Rooms"))
						filter = CompositeFilterOperator.and(filterHotel,filterStatusresv,filterOrDate);
					q.setFilter(filter).addSort("date", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
				}
			}else{
				filter = CompositeFilterOperator.and(filterHotel,filterOr);
				q.setFilter(filter).addSort("date", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
			}
			return GetList(datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()));
		}else if(TypePage=="CheckOutPending"||TypePage=="CheckOutPendingSingle"||TypePage=="CheckOutPendingGroup"){
			ReservationStatus fCheckin = gLogic.GetReservationStatus(hotelId,"Checked-in Rooms");
			statusResIdCheckin = String.valueOf(fCheckin.getId());
			ReservationStatus fresv = gLogic.GetReservationStatus(hotelId,"Checked-in Rooms");
			statusResIdresv = String.valueOf(fresv.getId());
			Filter filterHotel = new FilterPredicate("hotelId",
					FilterOperator.EQUAL, hotelId);
			Filter filterStatusCheckin = new FilterPredicate("ReservationStatus",
					FilterOperator.EQUAL, statusResIdCheckin);
			Filter filterStatusresv = new FilterPredicate("ReservationStatus",
					FilterOperator.EQUAL, statusResIdresv);
			Filter filterOr = CompositeFilterOperator.or(filterStatusCheckin,filterStatusresv);
			Filter filter = CompositeFilterOperator.and(filterHotel,filterOr);
			q.setFilter(filter).addSort("date", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);

			return GetList(datastore.prepare(q).asList(
					FetchOptions.Builder.withDefaults()));
		}else if(TypePage=="CheckInPending"||TypePage=="CheckInPendingGroup"||TypePage=="CheckInPendingSingle"){
			ReservationStatus fCheckin = gLogic.GetReservationStatus(hotelId,"Reserved Rooms");
			statusResIdCheckin = String.valueOf(fCheckin.getId());
			ReservationStatus fresv = gLogic.GetReservationStatus(hotelId,"Reserved Rooms");
			statusResIdresv = String.valueOf(fresv.getId());
			Filter filterHotel = new FilterPredicate("hotelId",
					FilterOperator.EQUAL, hotelId);
			Filter filterStatusCheckin = new FilterPredicate("ReservationStatus",
					FilterOperator.EQUAL, statusResIdCheckin);
			Filter filterStatusresv = new FilterPredicate("ReservationStatus",
					FilterOperator.EQUAL, statusResIdresv);
			Filter filterOr = CompositeFilterOperator.or(filterStatusCheckin,filterStatusresv);
			if(dateCheckin!=null&&dateCheckout!=null&&!dateCheckin.equals("")&&!dateCheckout.equals("")){
				Date dateCheckin_value = formatter.parse(dateCheckin);
				Date dateCheckout_value = formatter.parse(dateCheckout);
				if(!dateCheckin_value.equals("")&&!dateCheckout_value.equals("")){
					Filter filterDateCheckin = new FilterPredicate("date",FilterOperator.GREATER_THAN_OR_EQUAL, dateCheckin_value);
					Filter filterDateCheckout = new FilterPredicate("date",FilterOperator.LESS_THAN_OR_EQUAL, dateCheckout_value);
					Filter filterOrDate = CompositeFilterOperator.or(filterDateCheckin,filterDateCheckout);
					Filter filter = CompositeFilterOperator.and(filterHotel,filterOrDate,filterOr);
					q.setFilter(filter).addSort("date", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
				}
			}else{
				Filter filter = CompositeFilterOperator.and(filterHotel,filterOr);
				q.setFilter(filter).addSort("date", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
			}
			return GetList(datastore.prepare(q).asList(
					FetchOptions.Builder.withDefaults()));
		}else if(TypePage=="Deposits"||TypePage=="DepositsGroup"||TypePage=="DepositsSingle"){
			ReservationStatus fCheckin = gLogic.GetReservationStatus(hotelId,"Reserved Rooms");
			statusResIdCheckin = String.valueOf(fCheckin.getId());
			ReservationStatus fresv = gLogic.GetReservationStatus(hotelId,"Reserved Rooms");
			statusResIdresv = String.valueOf(fresv.getId());
			Filter filterHotel = new FilterPredicate("hotelId",
					FilterOperator.EQUAL, hotelId);
			Filter filterStatusCheckin = new FilterPredicate("ReservationStatus",
					FilterOperator.EQUAL, statusResIdCheckin);
			Filter filterStatusresv = new FilterPredicate("ReservationStatus",
					FilterOperator.EQUAL, statusResIdresv);
			Filter filterOr = CompositeFilterOperator.or(filterStatusCheckin,filterStatusresv);
			if(dateCheckin!=null&&dateCheckout!=null&&!dateCheckin.equals("")&&!dateCheckout.equals("")){
				Date dateCheckin_value = formatter.parse(dateCheckin);
				Date dateCheckout_value = formatter.parse(dateCheckout);
				if(!dateCheckin_value.equals("")&&!dateCheckout_value.equals("")){
					Filter filterDateCheckin = new FilterPredicate("date",FilterOperator.GREATER_THAN_OR_EQUAL, dateCheckin_value);
					Filter filterDateCheckout = new FilterPredicate("date",FilterOperator.LESS_THAN_OR_EQUAL, dateCheckout_value);
					Filter filterOrDate = CompositeFilterOperator.or(filterDateCheckin,filterDateCheckout);
					Filter filter = CompositeFilterOperator.and(filterHotel,filterOrDate,filterOr);
					q.setFilter(filter).addSort("date", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
				}
			}else{
				Filter filter = CompositeFilterOperator.and(filterHotel,filterOr);
				q.setFilter(filter).addSort("date", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
			}

			return GetList(datastore.prepare(q).asList(
					FetchOptions.Builder.withDefaults()));
		}else if(TypePage=="Temp"||TypePage=="TempGroup"||TypePage=="TempSingle"){
			ReservationStatus fCheckin = gLogic.GetReservationStatus(hotelId,"Temp Rooms");
			statusResIdCheckin = String.valueOf(fCheckin.getId());
			ReservationStatus fresv = gLogic.GetReservationStatus(hotelId,"Temp Rooms");
			statusResIdresv = String.valueOf(fresv.getId());
			Filter filterHotel = new FilterPredicate("hotelId",
					FilterOperator.EQUAL, hotelId);
			Filter filterStatusCheckin = new FilterPredicate("ReservationStatus",
					FilterOperator.EQUAL, statusResIdCheckin);
			Filter filterStatusresv = new FilterPredicate("ReservationStatus",
					FilterOperator.EQUAL, statusResIdresv);
			Filter filterOr = CompositeFilterOperator.or(filterStatusCheckin,filterStatusresv);
			if(dateCheckin!=null&&dateCheckout!=null&&!dateCheckin.equals("")&&!dateCheckout.equals("")){
				Date dateCheckin_value = formatter.parse(dateCheckin);
				Date dateCheckout_value = formatter.parse(dateCheckout);
				if(!dateCheckin_value.equals("")&&!dateCheckout_value.equals("")){
					Filter filterDateCheckin = new FilterPredicate("date",FilterOperator.GREATER_THAN_OR_EQUAL, dateCheckin_value);
					Filter filterDateCheckout = new FilterPredicate("date",FilterOperator.LESS_THAN_OR_EQUAL, dateCheckout_value);
					Filter filterOrDate = CompositeFilterOperator.or(filterDateCheckin,filterDateCheckout);
					Filter filter = CompositeFilterOperator.and(filterHotel,filterOrDate,filterOr);
					q.setFilter(filter).addSort("date", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
				}
			}else{
				Filter filter = CompositeFilterOperator.and(filterHotel,filterOr);
				q.setFilter(filter).addSort("date", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
			}
			return GetList(datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()));
		}else if(TypePage=="PaymentTracker"||TypePage=="PaymentTrackerGroup"||TypePage=="PaymentTrackerSingle"){
			ReservationStatus fCheckin = gLogic.GetReservationStatus(hotelId,"Checked-in Rooms");
			statusResIdCheckin = String.valueOf(fCheckin.getId());
			ReservationStatus fresv = gLogic.GetReservationStatus(hotelId,"Checked-in Rooms");
			statusResIdresv = String.valueOf(fresv.getId());
			Filter filterHotel = new FilterPredicate("hotelId",
					FilterOperator.EQUAL, hotelId);
			Filter filterStatusCheckin = new FilterPredicate("ReservationStatus",
					FilterOperator.EQUAL, statusResIdCheckin);
			Filter filterStatusresv = new FilterPredicate("ReservationStatus",
					FilterOperator.EQUAL, statusResIdresv);
			Filter filterOr = CompositeFilterOperator.or(filterStatusCheckin,filterStatusresv);
			if(dateCheckin!=null&&dateCheckout!=null&&!dateCheckin.equals("")&&!dateCheckout.equals("")){
				Date dateCheckin_value = formatter.parse(dateCheckin);
				Date dateCheckout_value = formatter.parse(dateCheckout);
				if(!dateCheckin_value.equals("")&&!dateCheckout_value.equals("")){
					Filter filterDateCheckin = new FilterPredicate("date",FilterOperator.GREATER_THAN_OR_EQUAL, dateCheckin_value);
					Filter filterDateCheckout = new FilterPredicate("date",FilterOperator.LESS_THAN_OR_EQUAL, dateCheckout_value);
					Filter filterOrDate = CompositeFilterOperator.or(filterDateCheckin,filterDateCheckout);
					Filter filter = CompositeFilterOperator.and(filterHotel,filterOrDate,filterOr);
					q.setFilter(filter).addSort("date", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
				}
			}else{
				Filter filter = CompositeFilterOperator.and(filterHotel,filterOr);
				q.setFilter(filter).addSort("date", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
			}
			return GetList(datastore.prepare(q).asList(
					FetchOptions.Builder.withDefaults()));
		}else if(TypePage=="GuestName"||TypePage=="GuestNameSingle"||TypePage=="GuestNameGroup"){
			ReservationStatus fCheckin = gLogic.GetReservationStatus(hotelId,"Checked-in Rooms");
			statusResIdCheckin = String.valueOf(fCheckin.getId());
			ReservationStatus fCheckout = gLogic.GetReservationStatus(hotelId,"Checked-out Rooms");
			statusResIdcheckout = String.valueOf(fCheckout.getId());
			Filter filterHotel = new FilterPredicate("hotelId",
					FilterOperator.EQUAL, hotelId);
			Filter filterStatusCheckin = new FilterPredicate("ReservationStatus",
					FilterOperator.EQUAL, statusResIdCheckin);
			Filter filterStatusCheckout = new FilterPredicate("ReservationStatus",
					FilterOperator.EQUAL, statusResIdcheckout);
			Filter filterOr = CompositeFilterOperator.or(filterStatusCheckin,filterStatusCheckout);
			Filter filter = null;
			if(dateCheckin!=null&&dateCheckout!=null&&!dateCheckin.equals("")&&!dateCheckout.equals("")){
				Date dateCheckin_value = formatter.parse(dateCheckin);
				Date dateCheckout_value = formatter.parse(dateCheckout);
				if(!dateCheckin_value.equals("")&&!dateCheckout_value.equals("")){
					Filter filterDateCheckin = new FilterPredicate("date",FilterOperator.GREATER_THAN_OR_EQUAL, dateCheckin_value);
					Filter filterDateCheckout = new FilterPredicate("date",FilterOperator.LESS_THAN_OR_EQUAL, dateCheckout_value);
					Filter filterOrDate = CompositeFilterOperator.or(filterDateCheckin,filterDateCheckout);
					if(type_reservation.equals("reservationType_A"))
						filter = CompositeFilterOperator.and(filterHotel,filterOrDate,filterOr);
					else if(type_reservation.equals("Checked-out Rooms"))
						filter = CompositeFilterOperator.and(filterHotel,filterOrDate,filterStatusCheckout);
					else if(type_reservation.equals("Checked-in Rooms"))
						filter = CompositeFilterOperator.and(filterHotel,filterOrDate,filterStatusCheckin);
					q.setFilter(filter).addSort("date", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
				}
			}else{
				if(type_reservation.equals("reservationType_A")||type_reservation.equals("Checked-out Rooms")||
						type_reservation.equals("Checked-in Rooms")||type_reservation.equals("")){
					if(type_reservation.equals("reservationType_A"))
						filter = CompositeFilterOperator.and(filterHotel,filterOr);
					else if(type_reservation.equals("Checked-out Rooms"))
						filter = CompositeFilterOperator.and(filterHotel,filterStatusCheckout);
					else if(type_reservation.equals("Checked-in Rooms"))
						filter = CompositeFilterOperator.and(filterHotel,filterStatusCheckin);
					else
						filter = CompositeFilterOperator.and(filterHotel,filterStatusCheckin);
					//filter = CompositeFilterOperator.and(filterHotel,filterOr);
				}
				q.setFilter(filter).addSort("date", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
			}
			
			return GetList(datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()));
		}else if(TypePage=="CancelResv"||TypePage=="CancelResvSingle"||TypePage=="CancelResvGroup"){
			ReservationStatus fCheckin = gLogic.GetReservationStatus(hotelId,"Cancel Reservation");
			statusResIdCheckin = String.valueOf(fCheckin.getId());
			ReservationStatus fresv = gLogic.GetReservationStatus(hotelId,"Cancel Reservation");
			statusResIdresv = String.valueOf(fresv.getId());
			Filter filterHotel = new FilterPredicate("hotelId",
					FilterOperator.EQUAL, hotelId);
			Filter filterStatusCheckin = new FilterPredicate("ReservationStatus",
					FilterOperator.EQUAL, statusResIdCheckin);
			Filter filterStatusresv = new FilterPredicate("ReservationStatus",
					FilterOperator.EQUAL, statusResIdresv);
			Filter filterOr = CompositeFilterOperator.or(filterStatusCheckin,filterStatusresv);
			if(dateCheckin!=null&&dateCheckout!=null&&!dateCheckin.equals("")&&!dateCheckout.equals("")){
				Date dateCheckin_value = formatter.parse(dateCheckin);
				Date dateCheckout_value = formatter.parse(dateCheckout);
				if(!dateCheckin_value.equals("")&&!dateCheckout_value.equals("")){
					Filter filterDateCheckin = new FilterPredicate("date",FilterOperator.GREATER_THAN_OR_EQUAL, dateCheckin_value);
					Filter filterDateCheckout = new FilterPredicate("date",FilterOperator.LESS_THAN_OR_EQUAL, dateCheckout_value);
					Filter filterOrDate = CompositeFilterOperator.or(filterDateCheckin,filterDateCheckout);
					Filter filter = CompositeFilterOperator.and(filterHotel,filterOrDate,filterOr);
					q.setFilter(filter).addSort("date", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
				}
			}else{
				Filter filter = CompositeFilterOperator.and(filterHotel,filterOr);
				q.setFilter(filter).addSort("date", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
			}
			return GetList(datastore.prepare(q).asList(
					FetchOptions.Builder.withDefaults()));
		}else if(TypePage=="NoShow"||TypePage=="NoShowSingle"||TypePage=="NoShowGroup"){
			ReservationStatus fCheckin = gLogic.GetReservationStatus(hotelId,"Cancel Reservation");
			statusResIdCheckin = String.valueOf(fCheckin.getId());
			ReservationStatus fresv = gLogic.GetReservationStatus(hotelId,"Cancel Reservation");
			statusResIdresv = String.valueOf(fresv.getId());
			Filter filterHotel = new FilterPredicate("hotelId",
					FilterOperator.EQUAL, hotelId);
			Filter filterStatusCheckin = new FilterPredicate("ReservationStatus",
					FilterOperator.EQUAL, statusResIdCheckin);
			Filter filterStatusresv = new FilterPredicate("ReservationStatus",
					FilterOperator.EQUAL, statusResIdresv);
			Filter filterOr = CompositeFilterOperator.or(filterStatusCheckin,filterStatusresv);
			if(dateCheckin!=null&&dateCheckout!=null&&!dateCheckin.equals("")&&!dateCheckout.equals("")){
				Date dateCheckin_value = formatter.parse(dateCheckin);
				Date dateCheckout_value = formatter.parse(dateCheckout);
				if(!dateCheckin_value.equals("")&&!dateCheckout_value.equals("")){
					Filter filterDateCheckin = new FilterPredicate("date",FilterOperator.GREATER_THAN_OR_EQUAL, dateCheckin_value);
					Filter filterDateCheckout = new FilterPredicate("date",FilterOperator.LESS_THAN_OR_EQUAL, dateCheckout_value);
					Filter filterOrDate = CompositeFilterOperator.or(filterDateCheckin,filterDateCheckout);
					Filter filter = CompositeFilterOperator.and(filterHotel,filterOrDate,filterOr);
					q.setFilter(filter).addSort("date", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
				}
			}else{
				Filter filter = CompositeFilterOperator.and(filterHotel,filterOr);
				q.setFilter(filter).addSort("date", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
			}
			return GetList(datastore.prepare(q).asList(
					FetchOptions.Builder.withDefaults()));
		}else{
			ReservationStatus fCheckin = gLogic.GetReservationStatus(hotelId,"Checked-in Rooms");
			statusResIdCheckin = String.valueOf(fCheckin.getId());
			ReservationStatus fresv = gLogic.GetReservationStatus(hotelId,"Reserved Rooms");
			statusResIdresv = String.valueOf(fresv.getId());
			Filter filterHotel = new FilterPredicate("hotelId",
					FilterOperator.EQUAL, hotelId);
			Filter filterStatusCheckin = new FilterPredicate("ReservationStatus",
					FilterOperator.EQUAL, statusResIdCheckin);
			Filter filterStatusresv = new FilterPredicate("ReservationStatus",
					FilterOperator.EQUAL, statusResIdresv);
			Filter filterOr = CompositeFilterOperator.or(filterStatusCheckin,filterStatusresv);
			Filter filter = CompositeFilterOperator.and(filterHotel,filterOr);
			
			q.setFilter(filter).addSort("date", SortDirection.ASCENDING).addSort("displayId", SortDirection.ASCENDING);
			return GetList(datastore.prepare(q).asList(
					FetchOptions.Builder.withDefaults()));
		}
		
	}
	public Group CreateGroup (HttpServletRequest req,HttpServletResponse resp,long hotelId, Date date, long span,String roomType, String PriceRateId,Double pay, long gusetId,
			String reason,String source,String note,long extrabed,String travelId,String creditCardId) 
			throws EntityNotFoundException, ParseException {
		long gId = 0;
		HttpSession session = req.getSession(true);
		String counterId =(String) session.getAttribute("currentCounter");
		GroupLogic groupLogic = new GroupLogic();
		Group group = new Group();
		group.setDate(date);
		group.setGuestString(String.valueOf(gusetId));
		group.setAgencyIdString("0");
		group.setDisplayId(groupLogic.GetMaxGroupDisplayId(hotelId)+1);
		group.setHotelId(hotelId);
		group.setPriceRateString(String.valueOf(PriceRateId));
		group.setNote(note);
		group.setListResvString(null);
		group.setSourcesString(source);
		group.setSpan(span);
		group.setExtrabed(extrabed);
		group.setReason(reason);
		group.setRoomtypeString(roomType);
		group.setCreditString(creditCardId);
		group.setTravelString(travelId);
		group.setChargeListString("");
		long paymentId = 0;
		Date payDate = new GenericLogic(req,resp).ServerDateTime(hotelId); // pao
		if (pay != 0) {
			PayType paytype = new PayTypeLogic()
					.GetPayType2(hotelId, "Cash");
			PaymentLogic pLogic = new PaymentLogic(req,resp);
			String paymode = String.valueOf(new MasterCreator().GetPayModeMaster("Cash").getId());
			Payment payment = pLogic.AddPayment(hotelId, pay,0, "", "0",
					payDate, paymode, String.valueOf(paytype.getId()), "", "",
					false,"",Long.parseLong(counterId));
			group.setPaymentListString(String.valueOf(payment.getId()));
		} else {
			group.setPaymentListString("");
		}
		Key kk = datastore.put(group.getEntity());
		gId = kk.getId();
		String gIdString = "G"+String.valueOf(gId);
		//Edit Res In Payment
		if (pay != 0) {
			PaymentLogic pLogic = new PaymentLogic(req,resp);
			pLogic.EditResIdPayment(hotelId, paymentId,gIdString);
		} 
		group.setId(kk.getId());
		group.setKey(kk);
		return group;
	}
	// /////////////////////CreateReservation from popup/////////////////////////////////////////////
	public Reservation CreateReservation(long hotelId, Date date, long span,
			String roomId, String roomType, String PriceRateId, long Adult,
			long Child, boolean Assign, String GuestId,
			String reservationStatus, long roomamount,
			String sources, long extrabed, String reason, String agencyId,
			Double pay,String guestnamelist,String guestsolutationlist,String guestlastnamelist,
			String guestphonelist,String guestemaillist) throws EntityNotFoundException, ParseException {
		Reservation rsv = new Reservation();
		if (roomamount > 1) {
			rsv = CreateGroupReservation(hotelId, date, span, roomId, roomType, PriceRateId, Adult,
					Child, Assign, GuestId,	reservationStatus, roomamount,
					sources, extrabed, reason, agencyId,
					pay, guestnamelist, guestsolutationlist,guestlastnamelist,
					guestphonelist, guestemaillist);
			
		} else if (roomamount == 1) {
			rsv = CreateSingleReservation(hotelId, date, span, roomId, roomType, PriceRateId, Adult,
					Child, Assign, GuestId,	reservationStatus, roomamount,
					sources, extrabed, reason, agencyId,
					pay, guestnamelist, guestsolutationlist,guestlastnamelist,
					guestphonelist, guestemaillist);
		}
		return rsv;
	}
	
	public Reservation CreateGroupReservation(long hotelId, Date date, long span,
			String roomId, String roomType, String PriceRateId, long Adult,
			long Child, boolean Assign, String GuestId,
			String reservationStatus, long roomamount,
			String sources, long extrabed, String reason, String agencyId,
			Double pay,String guestnamelist,String guestsolutationlist,String guestlastnamelist,
			String guestphonelist,String guestemaillist) throws EntityNotFoundException, ParseException {

		AuditTrailLogic auditTrail = new AuditTrailLogic(req,resp);
		DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
		Group group = new Group();

		int rsvComplete = 0;
		Reservation rsv = new Reservation();

		String[] arrayK = new String[(int) roomamount];
		String[] arrayChargeList = new String[(int) roomamount];
		HttpSession session = req.getSession(true);
		GroupLogic groupLogic = new GroupLogic();
		String counterId =(String) session.getAttribute("currentCounter");
		group.setDate(date);
		group.setAgencyIdString(agencyId);
		group.setDisplayId(groupLogic.GetMaxGroupDisplayId(hotelId)+1);
		group.setHotelId(hotelId);
		group.setPriceRateString(String.valueOf(PriceRateId));
		group.setGuestString(GuestId);
		group.setNote("");
		group.setListResvString(null);
		group.setSourcesString(sources);
		group.setSpan(span);
		group.setExtrabed(extrabed);
		group.setReason(reason);
		group.setRoomtypeString(roomType);
		group.setCreditString("0");
		group.setTravelString("0");
		group.setChargeListString("");
		group.setObjective("");
		long paymentId = 0;
		Date payDate = new GenericLogic(req,resp).ServerDateTime(hotelId); // pao
		if (pay != 0) {
			PayType paytype = new PayTypeLogic()
				.GetPayType2(hotelId, "Cash");
			String paymode = String.valueOf(new MasterCreator().GetPayModeMaster("Cash").getId());
			PaymentLogic pLogic = new PaymentLogic(req,resp);
			Payment payment = pLogic.AddPayment(hotelId, pay,0, "", "0",
					payDate, paymode, String.valueOf(paytype.getId()), "", "",
					false,"",Long.parseLong(counterId));
			group.setPaymentListString(String.valueOf(payment.getId()));
			paymentId = payment.getId();
		} else {
			group.setPaymentListString("");
		}
		Key kk = datastore.put(group.getEntity());
		long gId = kk.getId();
		group.setId(gId);
		group.setKey(kk);
		//Edit Res In Payment
		String grupIdString = "G"+String.valueOf(gId);
		if (pay != 0) {
			PaymentLogic pLogic = new PaymentLogic(req,resp);
			pLogic.EditResIdPayment(hotelId, paymentId,grupIdString);
		} 
		List<SubReservation> subRsv = GetUsedRoomWithinDate(hotelId,date,span,Long.parseLong(roomType));
		List<Room> r = new PopupLogic(req,resp).LoadRoomWithCache(hotelId, Long.parseLong(roomType));
		SubReservation lastSub = new SubReservationLogic(req,resp).GetLastSubRes(subRsv);
		for(SubReservation s: subRsv)
		{
			if(s.getDateTo().equals(lastSub.getDateTo()) && GetReservation(s.getParentId()).getSellRoom())
				continue;
			for(int i=0;i<r.size();i++)
				if(r.get(i).getId() == s.getRoom().getId())
				{
					r.remove(i);
					break;
				}
		}
		int indexRoom = 0;
		for (indexRoom = 0; indexRoom < r.size(); indexRoom++)
			if (r.get(indexRoom).getId() == Long.parseLong(roomId))
				break;
		
		if(r.size() < roomamount)
			return null;
		long maxDisplayId = GetMaxResvDisplayId(hotelId);
		for (rsvComplete = 0; rsvComplete < roomamount; rsvComplete++) {
			rsv = new Reservation();
			rsv.setDisplayId(maxDisplayId+rsvComplete+1);
			rsv.setRoom(r.get(indexRoom));
			indexRoom++; if(indexRoom >= r.size()) indexRoom = 0;
			rsv.setHotelId(hotelId);
			rsv.setDate(date);
			rsv.setSpan(span);
			rsv.setAgencyIdString(agencyId);
			rsv.setRoomTypeString(String.valueOf(roomType));
			rsv.setGuestString("0");
		
			PackageByDate packagebydate = new PackageLogic(req,resp).AddPackageByDate(PriceRateId, date, Util.addDays(date, span));
			rsv.setPackageByDateString(String.valueOf(packagebydate.getId()));
			rsv.setAdult(Adult);
			rsv.setChild(Child);
			rsv.setAssign(Assign);
			rsv.setReservationStatusString(String.valueOf(reservationStatus));
			long order = 1;
			for(SubReservation s: subRsv)
				if(Util.addDays(s.getDateTo(), -1).equals(date))
					order++;
			rsv.setOrder(order);
			rsv.setNote("");
			rsv.setCreditString("0");
			rsv.setGroupIdString(String.valueOf(gId));
			rsv.setGroupIdNumber(gId);
			rsv.setAgencyIdString(agencyId);
			rsv.setExtrabed(extrabed);
			rsv.setPaymentListString("");
			ChargeLogic cLogic = new ChargeLogic(req,resp);
			String chargeList = "";
			
			TaxLogic taxLogic = new TaxLogic(req,resp);
			for(int x = 0;x<span;x++){
				Date tmpDate = Util.addDays(date, x);
				double price = cLogic.CalPrice(rsv.getRoomType(),rsv.getPackage(tmpDate).getPackages(),rsv);
				HashMap<String,Double> calTax = taxLogic.CalRoomTax(hotelId,price,x);
				
				Charge c = cLogic.AddCharge(hotelId, "Room Rate",0,
					calTax.get("costIncludeTax"), Util.addDays(date, x), (double) 0, "0", calTax.get("tax"), false, true,true,0,null,null);
				if(x == span-1)
					chargeList += String.valueOf(c.getId()); 
				else
					chargeList += String.valueOf(c.getId())+","; 
				arrayChargeList[rsvComplete] = String.valueOf(c.getId());
			}
			rsv.setChargeListString(chargeList);
				
			rsv.setAvaliable(true);
			rsv.setStatus(true);
			Key k = datastore.put(rsv.getEntity());
			rsv.setId(k.getId());
			rsv.setKey(k);
			arrayK[rsvComplete] = String.valueOf(k.getId());
		}
		
		if (gId != 0) {
			List<String> listResev = Arrays.asList(arrayK);
			String listN = listResev.toString().replace("[", "")
					.replace("]", "").trim();
			Group g = GetGroup(gId);
			g.setListResvString(listN);
			Key k = datastore.put(g.getEntity());
			g.setId(k.getId());
			g.setKey(k);
		}

		auditTrail.addAuditTrail(
				rsv,
				String.format(getResourceBundle("AuditTrail.Reservation.GroupReservationWithCash"),
					getUser(),
					df.format(date),
					df.format(Util.addDays(date,span)),
					pay,
					"Baht",
					Adult,
					Child
					));
		return rsv;
	}
	
	public Reservation CreateSingleReservation(long hotelId, Date date, long span,
			String roomId, String roomType, String PriceRateId, long Adult,
			long Child, boolean Assign, String GuestId,
			String reservationStatus, long roomamount,
			String sources, long extrabed, String reason, String agencyId,
			Double pay,String guestnamelist,String guestsolutationlist,String guestlastnamelist,
			String guestphonelist,String guestemaillist) throws EntityNotFoundException, ParseException {

		String[] arrayChargeList = new String[(int) roomamount];
		Reservation rsv = new Reservation();
		DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
		
		boolean canbeMove = true;
		List<SubReservation> sub = GetReservationWithinDateInSpecificRoom(hotelId, date, span, Long.parseLong(roomId));
		for(SubReservation s:sub)
			if(!s.isSellRoom() && (s.isAssign(this) || !CanBeChangeRoomWithSellRoom(s))) { canbeMove = false; break; }
		if(canbeMove){
			long order = 1;
			for(SubReservation s:sub){
				if(!s.isSellRoom())
					AutoMoveRoomWithSellRoom(s);
				else if(Util.addDays(s.getDateTo(),-1).equals(date))
					order++;
			}
		
			Guest guest = new Guest();
			GuestLogic guestLogic = new GuestLogic(req,resp);
			String additionalguestlist = GuestId;
			if(guestnamelist != null ){
				if(!guestnamelist.equals("")){
					for(int i = 0; i< guestnamelist.split(",").length;i++){
						guest = guestLogic.AddGuest(Long.parseLong(guestsolutationlist.split(",")[i]), guestnamelist.split(",")[i], guestlastnamelist.split(",")[i], guestphonelist.split(",")[i], guestemaillist.split(",")[i]);
						if(i == 0){
							additionalguestlist += ","+guest.getId()+",";
						}else if(i != guestnamelist.split(",").length -1){
							additionalguestlist += guest.getId()+",";
						}else{
							additionalguestlist += guest.getId();
						}
					}
				}
			}
			
			rsv.setDisplayId(GetMaxResvDisplayId(hotelId)+1);
			rsv.setHotelId(hotelId);
			rsv.setDate(date);
			rsv.setSpan(span);
			rsv.setRoomString(String.valueOf(roomId));
			rsv.setRoomTypeString(String.valueOf(roomType));
			rsv.setGuestString(String.valueOf(GuestId));
			rsv.setAdditionalGuestString(additionalguestlist);
			PackageByDate packagebydate = new PackageLogic(req,resp)
				.AddPackageByDate(PriceRateId, date, Util.addDays(date, span));
			rsv.setPackageByDateString(String.valueOf(packagebydate.getId()));
			rsv.setAdult(Adult);
			rsv.setChild(Child);
			rsv.setAssign(Assign);
			rsv.setReservationStatusString(String
				.valueOf(reservationStatus));
			rsv.setOrder(order);
			rsv.setNote("");
			rsv.setObjective("");
			rsv.setGroupIdString("0");
			rsv.setGroupIdNumber(0);
			rsv.setCreditString("0");
			rsv.setAgencyIdString(agencyId);
			rsv.setExtrabed(extrabed);
			long rId = 0;
			long paymentId = 0;
			HttpSession session = req.getSession(true);
			String counterId =(String) session.getAttribute("currentCounter");
			Date payDate = new GenericLogic(req,resp).ServerDateTime(hotelId);// pao
			if (pay != 0) {
				String paymode = String.valueOf(new MasterCreator().GetPayModeMaster("Cash").getId());
				PayType paytype = new PayTypeLogic().GetPayType2(hotelId,
						"Cash");
				PaymentLogic pLogic = new PaymentLogic(req,resp);
				Payment payment = pLogic.AddPayment(hotelId, pay,0, "", "0",
						payDate, paymode, String.valueOf(paytype.getId()), "",
						"", false,"",Long.parseLong(counterId));
				rsv.setPaymentListString(String.valueOf(payment.getId()));
				paymentId = payment.getId();
			} else {
				rsv.setPaymentListString("");
			}
			ChargeLogic cLogic = new ChargeLogic(req,resp);
			TaxLogic taxLogic = new TaxLogic(req,resp);
			String chargeList = "";
			
			for(int x = 0;x<span;x++){
				Date tmpDate = Util.addDays(date, x);
				double price = cLogic.CalPrice(rsv.getRoomType(),rsv.getPackage(tmpDate).getPackages(),rsv);
				HashMap<String,Double> calTax = taxLogic.CalRoomTax(hotelId,price,x);
				
				Charge c = cLogic.AddCharge(hotelId, "Room Rate",0,
						calTax.get("costIncludeTax"), Util.addDays(date, x), (double) 0, "0", calTax.get("tax"), false, true,true,0,null,null);
				if(x == span-1){
					chargeList += String.valueOf(c.getId()); 
				}else{
					chargeList += String.valueOf(c.getId())+","; 
				}
				arrayChargeList[0] = String.valueOf(c.getId());
			}
			rsv.setChargeListString(chargeList);
			rsv.setAvaliable(true);
			rsv.setStatus(true);
			Key k = datastore.put(rsv.getEntity());
			rId = k.getId();
			rsv.setId(rId);
			rsv.setKey(k);
			//Edit Res In Payment
			String rIdString = String.valueOf(rId);
			if (pay != 0) {
				PaymentLogic pLogic = new PaymentLogic(req,resp);
				pLogic.EditResIdPayment(hotelId, paymentId,rIdString);
			} 
		}

		AuditTrailLogic auditTrail = new AuditTrailLogic(req,resp);
		auditTrail.addAuditTrail(
				rsv,
				String.format(getResourceBundle("AuditTrail.Reservation.ReservationWithCash"),
					getUser(),
					df.format(date),
					df.format(Util.addDays(date,span)),
					pay,
					"Baht",
					Adult,
					Child
					));
		return rsv;
	}
	
	public long GetMaxResvDisplayId(long hotelId)
	{
		Query q = new Query(EntityName.Reservation);

		Filter filterHotel = new FilterPredicate("hotelId",
				FilterOperator.EQUAL, hotelId);
		q.setFilter(filterHotel).addSort("displayId", SortDirection.DESCENDING);

		List<Reservation> list = GetReservationAll(datastore.prepare(q).asList(
				FetchOptions.Builder.withLimit(1)));
		if(list.size()>0)
			return list.get(0).getDisplayId();
		return 0;
	}
	
	public Reservation EditReservation(long hotelId, long resId,
			String rsvStatus, boolean sellRoom, boolean isAssign, Date dateCheckin)
			throws EntityNotFoundException, ParseException {
		Reservation rsv = GetReservation(resId);
		ReservationStatus f = new GenericLogic(req,resp).GetReservationStatus(hotelId,
				rsvStatus);
		if(rsvStatus.equals("Checked-in Rooms")||rsvStatus.equals("Checked-out Rooms")||isAssign){
			rsv.setAssign(true);
		}else{
			rsv.setAssign(false);
		}
		rsv.setReservationStatusString(String.valueOf(f.getId()));
		rsv.setSellRoom(sellRoom);
	//	rsv.setAssign(isAssign);
		if(!dateCheckin.equals(null)||!dateCheckin.equals("")){
			rsv.setDateCheckin(dateCheckin);
		}
		Key k = datastore.put(rsv.getEntity());
		rsv.setId(k.getId());
		rsv.setKey(k);

		return rsv;
	}
	public Reservation EditResGuestId(long hotelId, long resId,String guestId)
			throws EntityNotFoundException, ParseException {
		Reservation rsv = GetReservation(resId);
		rsv.setGuestString(guestId);
		Key k = datastore.put(rsv.getEntity());
		rsv.setId(k.getId());
		rsv.setKey(k);

		return rsv;
	}
	public Group SaveNote(long hotelId, long groupId, String note)
			throws EntityNotFoundException, ParseException {
		Group g = GetGroup(groupId);
		g.setNote(note);
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);

		return g;
	}
	public Reservation SaveNoteS(long hotelId, long resId, String note)
			throws EntityNotFoundException, ParseException {
		Reservation rsv = GetReservation(resId);
		rsv.setNote(note);
		Key k = datastore.put(rsv.getEntity());
		rsv.setId(k.getId());
		rsv.setKey(k);

		return rsv;
	}
	public Reservation GetReservation(long id) {
		Key key = KeyFactory.createKey(EntityName.Reservation, id);
		try {
			Entity lang = datastore.get(key);
			Reservation c = new Reservation();
			c.setEntity(lang);
			
			return c;
		} catch (EntityNotFoundException e) {
			return null;
		}
	}
	public List<Reservation> GetReservationAll(List<Entity> entities) {
		List<Reservation> list = new ArrayList<Reservation>();
		if(entities!=null)
		for (Entity e : entities) {
			Reservation a = new Reservation();
			a.setEntity(e);
			list.add(a);
		}
		return list;
	}
	public Group GetGroup(long id) {
		Key key = KeyFactory.createKey(EntityName.Group, id);
		try {
			Entity lang = datastore.get(key);
			Group c = new Group();
			c.setEntity(lang);
			return c;
		} catch (EntityNotFoundException e) {
			return null;
		}
	}
	public Reservation GetReservation(String GuestId, Date date, long order,
			long roomId, long roomType) {

		Filter filterGuestId = new FilterPredicate("GuestId",
				FilterOperator.EQUAL, GuestId);
		Filter filterOrder = new FilterPredicate("order", FilterOperator.EQUAL,
				order);
		Filter filterDate = new FilterPredicate("date", FilterOperator.EQUAL,
				date);
		Filter filterroomId = new FilterPredicate("roomId",
				FilterOperator.EQUAL, String.valueOf(roomId));
		Filter filterroomType = new FilterPredicate("roomType",
				FilterOperator.EQUAL, String.valueOf(roomType));
		Filter filter = CompositeFilterOperator.and(filterGuestId, filterDate,
				filterOrder, filterroomId, filterroomType);
		Query q = new Query(EntityName.Reservation).setFilter(filter);
		PreparedQuery pq = datastore.prepare(q);
		try {
			Entity e = pq.asSingleEntity();

			Reservation n = new Reservation();
			n.setEntity(e);

			return n;
		} catch (Exception e) {
			return null;
		}
	}
	public Reservation GetReservation(Date date, long roomId, long roomType) {

		Filter filterDate = new FilterPredicate("date", FilterOperator.EQUAL,
				date);
		Filter filterroomId = new FilterPredicate("roomId",
				FilterOperator.EQUAL, String.valueOf(roomId));
		Filter filterroomType = new FilterPredicate("roomType",
				FilterOperator.EQUAL, String.valueOf(roomType));
		Filter filter = CompositeFilterOperator.and(filterDate, filterroomId,
				filterroomType);
		Query q = new Query(EntityName.Reservation).setFilter(filter);
		PreparedQuery pq = datastore.prepare(q);
		try {
			Entity e = pq.asSingleEntity();

			Reservation n = new Reservation();
			n.setEntity(e);

			return n;
		} catch (Exception e) {
			return null;
		}
	}
	public List<Reservation> GetAllGuestMapping(long hotelId) {
		Query q = new Query(EntityName.Reservation);

		Filter filterHotel = new FilterPredicate("hotelId",
				FilterOperator.EQUAL, hotelId);
		q.setFilter(filterHotel);

		return GetList(datastore.prepare(q).asList(
				FetchOptions.Builder.withDefaults()));
	}
	public List<Reservation> GetRoomUsed(long hotelId, Date date, long roomtype) {
		Query q = new Query(EntityName.Reservation);

		Filter filterhotelId = new FilterPredicate("hotelId",
				FilterOperator.EQUAL, hotelId);
		Filter filterDate = new FilterPredicate("date",
				FilterOperator.LESS_THAN_OR_EQUAL, date);
		Filter filterroomType = new FilterPredicate("roomType",
				FilterOperator.EQUAL, String.valueOf(roomtype));
		Filter filter = CompositeFilterOperator.and(filterhotelId, filterDate,
				filterroomType);
		q.setFilter(filter);
		return GetList(datastore.prepare(q).asList(
				FetchOptions.Builder.withDefaults()));
	}
	
	// find reservation/subreservation/DNR which use ...room within spacific date
	public List<SubReservation> GetUsedRoomWithinDate(long hotelId,Date date,long span, long roomtype)
	{
		Query q = new Query(EntityName.Reservation);
		Filter filterhotelId = new FilterPredicate("hotelId",
				FilterOperator.EQUAL, hotelId);
		Filter filterDate = new FilterPredicate("dateTo",
				FilterOperator.GREATER_THAN, date);
		Filter filterroomType = new FilterPredicate("roomType",
				FilterOperator.EQUAL, String.valueOf(roomtype));
		Filter filterSubReservation1 = new FilterPredicate("subReservationList",
				FilterOperator.EQUAL, "");
		Filter filterSubReservation2 = new FilterPredicate("subReservationList",
				FilterOperator.EQUAL, null);
		Filter filterSubReservation = CompositeFilterOperator.or(filterSubReservation1,filterSubReservation2);
		Filter filter = CompositeFilterOperator.and(filterhotelId, filterDate,
				filterroomType,filterSubReservation);
		q.setFilter(filter);
		List<Reservation> list1 = GetList(datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()));
		
		Query q2 = new Query(EntityName.SubReservation);
		Filter filterQ2 = CompositeFilterOperator.and(filterhotelId, filterDate,
				filterroomType);
		q2.setFilter(filterQ2);
		List<SubReservation> list2 = GetSubReservationList(datastore.prepare(q2).asList(FetchOptions.Builder.withDefaults()));
		
		DNRLogic dnrLogic = new DNRLogic(req,resp);
		RoomLogic roomLogic = new RoomLogic(req,resp);
		List<DNR> list3 = dnrLogic.GetExistDNR(hotelId, date);
		
		List<SubReservation> result = new ArrayList<SubReservation>();
		
		for(Reservation r : list1)
		{
			if(r.getDate().after(Util.addDays(date,span -1)))
				continue;
			SubReservation subResv = new SubReservation();
			subResv.CloneReservation(r);
			result.add(subResv);
		}
		for(SubReservation s : list2)
		{
			if(s.getDate().after(Util.addDays(date, span -1)))
				continue;
			result.add(s);
		}
		for(DNR dnr : list3)
		{
			if(dnr.getDate().after(Util.addDays(date, span -1)))
				continue;
			Room room = roomLogic.GetRoom(dnr.getRoomId());
			if(Long.parseLong(room.getRoomtypeString()) != roomtype)
				continue;
			Reservation r = dnrLogic.DNRtoReservation(dnr);
			SubReservation subResv = new SubReservation();
			subResv.CloneReservation(r);
			result.add(subResv);
		}
		
		return result;
	}
	public List<SubReservation> GetUsedRoomWithinDateWithAssign(long hotelId,Date date,long span, long roomtype) throws IOException
	{
		Query q = new Query(EntityName.Reservation);
		Filter filterhotelId = new FilterPredicate("hotelId",
				FilterOperator.EQUAL, hotelId);
		Filter filterDate = new FilterPredicate("dateTo",
				FilterOperator.GREATER_THAN, date);
		Filter filterroomType = new FilterPredicate("roomType",FilterOperator.EQUAL, String.valueOf(roomtype));
		Filter filterSubReservation1 = new FilterPredicate("subReservationList",FilterOperator.EQUAL, "");
		Filter filterSubReservation2 = new FilterPredicate("subReservationList",FilterOperator.EQUAL, null);
		Filter filterSubReservation = CompositeFilterOperator.or(filterSubReservation1,filterSubReservation2);
		Filter filter = CompositeFilterOperator.and(filterhotelId, filterDate,filterroomType,filterSubReservation);
		q.setFilter(filter);
		List<Reservation> list1 = GetList(datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()));
		DNRLogic dnrLogic = new DNRLogic(req,resp);
		RoomLogic roomLogic = new RoomLogic(req,resp);
		List<DNR> list3 = dnrLogic.GetExistDNR(hotelId, date);
		Query q2 = new Query(EntityName.SubReservation);
		Filter filterQ2 = CompositeFilterOperator.and(filterhotelId, filterDate,
				filterroomType);
		q2.setFilter(filterQ2);
		List<SubReservation> list2 = GetSubReservationList(datastore.prepare(q2).asList(FetchOptions.Builder.withDefaults()));
		List<SubReservation> result = new ArrayList<SubReservation>();
				
		for(Reservation r : list1)
		{
			if(r.getDate().after(Util.addDays(date,span -1)))
				continue;
			if(r.isAssign())
			{
				SubReservation subResv = new SubReservation();
				subResv.CloneReservation(r);
				result.add(subResv);
			}
			if(!CanBeChangeRoom(r))
			{
				SubReservation subResv = new SubReservation();
				subResv.CloneReservation(r);
				result.add(subResv);	
			}
		}
		
		for(SubReservation s : list2)
		{
			if(s.getDate().after(Util.addDays(date, span -1)))
				continue;
			result.add(s);
		}
		for(DNR dnr : list3)
		{
			if(dnr.getDate().after(Util.addDays(date, span -1)))
				continue;
			Room room = roomLogic.GetRoom(dnr.getRoomId());
			if(Long.parseLong(room.getRoomtypeString()) != roomtype)
				continue;
			Reservation r = dnrLogic.DNRtoReservation(dnr);
			SubReservation subResv = new SubReservation();
			subResv.CloneReservation(r);
			result.add(subResv);
		}
		return result;
	}
	public List<SubReservation> GetReservationWithinDateInSpecificRoom(long hotelId,Date date, long span, long roomId)
	{
		Query q = new Query(EntityName.Reservation);
		Filter filterhotelId = new FilterPredicate("hotelId",
				FilterOperator.EQUAL, hotelId);
		Filter filterDate = new FilterPredicate("dateTo",
				FilterOperator.GREATER_THAN, date);
		Filter filterRoom = new FilterPredicate("room",
				FilterOperator.EQUAL, String.valueOf(roomId));
		Filter filterRoomId = new FilterPredicate("roomId",
				FilterOperator.EQUAL, String.valueOf(roomId));
		Filter filterSubReservation1 = new FilterPredicate("subReservationList",
				FilterOperator.EQUAL, "");
		Filter filterSubReservation2 = new FilterPredicate("subReservationList",
				FilterOperator.EQUAL, null);
		Filter filterSubReservation = CompositeFilterOperator.or(filterSubReservation1,filterSubReservation2);
		Filter filter = CompositeFilterOperator.and(filterhotelId, filterDate,
				filterRoomId,filterSubReservation);
		q.setFilter(filter);
		List<Reservation> list1 = GetList(datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()));
		
		Query q2 = new Query(EntityName.SubReservation);
		Filter filterQ2 = CompositeFilterOperator.and(filterhotelId, filterDate,
				filterRoom);
		q2.setFilter(filterQ2);
		List<SubReservation> list2 = GetSubReservationList(datastore.prepare(q2).asList(FetchOptions.Builder.withDefaults()));
		
		DNRLogic dnrLogic = new DNRLogic(req,resp);
		List<DNR> list3 = dnrLogic.GetExistDNR(hotelId, date, roomId);
		
		List<SubReservation> result = new ArrayList<SubReservation>();
		
		for(Reservation r : list1)
		{
			if(r.getDate().after(Util.addDays(date,span -1)))
				continue;
			SubReservation subResv = new SubReservation();
			subResv.CloneReservation(r);
			result.add(subResv);
		}
		for(SubReservation s : list2)
		{
			if(s.getDate().after(Util.addDays(date, span -1)))
				continue;
			result.add(s);
		}
		for(DNR dnr : list3)
		{
			if(dnr.getDate().after(Util.addDays(date, span -1)))
				continue;
			Reservation r = dnrLogic.DNRtoReservation(dnr);
			SubReservation subResv = new SubReservation();
			subResv.CloneReservation(r);
			result.add(subResv);
		}
		
		return result;
	}
	//check another room (same roomtype) is clear for move res
	public boolean CanBeChangeRoom(Reservation res)
	{
		long hotelId = res.getHotelId();
		long roomtype = res.getRoomType().getId();
		
		List<SubReservation> subRsv = GetUsedRoomWithinDate(hotelId,res.getDate(),res.getSpan(),roomtype);
		List<Room> obj = new PopupLogic(req,resp).LoadRoomWithCache(hotelId, roomtype);
		
		for(SubReservation s: subRsv)
		{
			for(int i=0;i<obj.size();i++)
				if(obj.get(i).getId() == s.getRoom().getId())
				{
					obj.remove(i);
					break;
				}
		}
		
		if(obj.size() > 0) return true;
		else return false;
	}
	// if room is clean and set sell room is canbe change
	public boolean CanBeChangeRoomWithSellRoom(Reservation res)
	{
		long hotelId = res.getHotelId();
		long roomtype = res.getRoomType().getId();
		
		List<SubReservation> subRsv = GetUsedRoomWithinDate(hotelId,res.getDate(),res.getSpan(),roomtype);
		List<Room> obj = new PopupLogic(req,resp).LoadRoomWithCache(hotelId, roomtype);
		
		for(SubReservation s: subRsv)
		{
			if(s.isSellRoom() && s.getSellRoomDate() == Util.addDays(s.getDateTo(), -1))
				continue;
			for(int i=0;i<obj.size();i++)
				if(obj.get(i).getId() == s.getRoom().getId())
				{
					obj.remove(i);
					break;
				}
		}
		
		if(obj.size() > 0) return true;
		else return false;
	}
	//check another room (same roomtype) is clear for move subres
	public boolean CanBeChangeRoom(SubReservation subRes){
		List<Room> obj = GetBlankRoomWhichCanBeChangeRoom(subRes);
		
		if(obj.size() > 0) return true;
		else return false;
	}
	
	public List<Room> GetBlankRoomWhichCanBeChangeRoom(SubReservation subRes)
	{
		long hotelId = subRes.getHotelId();
		long roomtype = subRes.getRoomType().getId();
		
		List<SubReservation> subRsv = GetUsedRoomWithinDate(hotelId,subRes.getDate(),subRes.getSpan(),roomtype);
		List<Room> obj = new PopupLogic(req,resp).LoadRoomWithCache(hotelId, roomtype);
		
		for(SubReservation s: subRsv)
		{
			for(int i=0;i<obj.size();i++)
				if(s.isAssign(this) && obj.get(i).getId() == s.getRoom().getId())
				{
					obj.remove(i);
					break;
				}
		}
		
		return obj;
	}
	// if room is clean and set sell room is canbe change
	public boolean CanBeChangeRoomWithSellRoom(SubReservation subRes)
	{
		List<Room> obj = GetBlankRoomWhichCanBeChangeRoomWithSellRoom(subRes);
		if(obj.size() > 0) return true;
		else return false;
	}
	public List<Room>GetBlankRoomWhichCanBeChangeRoomWithSellRoom(SubReservation subRes)
	{
		long hotelId = subRes.getHotelId();
		long roomtype = subRes.getRoomType().getId();
		
		List<SubReservation> subRsv = GetUsedRoomWithinDate(hotelId,subRes.getDate(),subRes.getSpan(),roomtype);
		return GetBlankRoomWhichCanBeChangeRoomWithSellRoom(subRes,subRsv);
	}
	public List<Room> GetBlankRoomWhichCanBeChangeRoomWithSellRoom(SubReservation subRes,List<SubReservation> subRsv)
	{
		long hotelId = subRes.getHotelId();
		long roomtype = subRes.getRoomType().getId();
		
		List<Room> obj = new PopupLogic(req,resp).LoadRoomWithCache(hotelId, roomtype);
		
		for(SubReservation s: subRsv)
		{
			if(s.isSellRoom() && s.getSellRoomDate() == Util.addDays(s.getDateTo(), -1))
				continue;
			for(int i=0;i<obj.size();i++)
				if(s.isAssign(this) && obj.get(i).getId() == s.getRoom().getId())
				{
					obj.remove(i);
					break;
				}
		}
		return obj;
	}
	//check subres/res in that room canbe move to another room
	public boolean CanBeMoveToRoom(SubReservation res, long roomId)
	{
		List<SubReservation> list = GetReservationWithinDateInSpecificRoom(res.getHotelId(), res.getDate(), res.getSpan(), roomId);
		if(list == null || list.size() == 0)
			return true;
		
		for(SubReservation s : list)
			if(s.isAssign(this) || !CanBeChangeRoom(s))
				return false;
		return true;
	}
	public boolean CanBeMoveToRoomWithSellRoom(SubReservation res, long roomId)
	{
		List<SubReservation> list = GetReservationWithinDateInSpecificRoom(res.getHotelId(), res.getDate(), res.getSpan(), roomId);
		if(list == null || list.size() == 0)
			return true;
		
		for(SubReservation s : list)
			if(s.isAssign(this) || !CanBeChangeRoomWithSellRoom(s))
				return false;
		return true;
	}
	public boolean CanBeMoveToRoom(Reservation res, long roomId)
	{
		List<SubReservation> list = GetReservationWithinDateInSpecificRoom(res.getHotelId(), res.getDate(), res.getSpan(), roomId);
		if(list == null || list.size() == 0)
			return true;
		
		for(SubReservation s : list)
			if(s.isAssign(this) || !CanBeChangeRoom(s))
				return false;
		return true;
	}
	public boolean CanBeMoveToRoomWithSellRoom(Reservation res, long roomId)
	{
		List<SubReservation> list = GetReservationWithinDateInSpecificRoom(res.getHotelId(), res.getDate(), res.getSpan(), roomId);
		if(list == null || list.size() == 0)
			return true;
		
		for(SubReservation s : list)
			if(s.isAssign(this) ||!CanBeChangeRoomWithSellRoom(s))
				return false;
		return true;
	}
	
	public boolean CanBeMoveToRoomExceptSpecificResv(long hotelId,Date date, long span, long roomId, List<Long> exceptId)
	{
		List<SubReservation> list = GetReservationWithinDateInSpecificRoom(hotelId, date, span, roomId);
		for(SubReservation s : list)
		{
			boolean foundAnother = false;
			for(long id : exceptId)
				if((s.getId() == -1 && s.getParentId() != id) ||
					(s.getId() > 0 && s.getId() != id))
					foundAnother = true;
			if(foundAnother)
				return false;
		}
		return true;
	}
	//find next room (same roomtype) which clear for move res
	public Room GetNextAvaliableNextRoom(SubReservation subRes)
	{
		long hotelId = subRes.getHotelId();
		long room = subRes.getRoom().getId();
		long roomtype = subRes.getRoomType().getId();
		
		List<SubReservation> subResFromDB = GetUsedRoomWithinDate(hotelId,subRes.getDate(),subRes.getSpan(),roomtype);
		List<Room> obj = new PopupLogic(req,resp).LoadRoomWithCache(hotelId, roomtype);
		
		for(SubReservation s:subResFromDB)
			for(int i=0;i<obj.size();i++)
				if(obj.get(i).getId() == s.getRoom().getId() && s.getRoom().getId() != room)
				{
					obj.remove(i);
					break;
				}
		
		int i = 0;
		for(i=0;i<obj.size();i++)
			if(obj.get(i).getId() == room)
				break;
		if(i < (obj.size() - 1))
			return obj.get(i+1);
		else
			return obj.get(0);
	}
	public Room GetNextAvaliableNextRoomWithSellRoom(SubReservation subRes)
	{
		long hotelId = subRes.getHotelId();
		long roomtype = subRes.getRoomType().getId();
		
		List<SubReservation> subResFromDB = GetUsedRoomWithinDate(hotelId,subRes.getDate(),subRes.getSpan(),roomtype);
		return GetNextAvaliableNextRoomWithSellRoom(subRes,subResFromDB);
	}
	public Room GetNextAvaliableNextRoomWithSellRoom(SubReservation subRes,List<SubReservation> subResFromDB)
	{
		long hotelId = subRes.getHotelId();
		long room = subRes.getRoom().getId();
		long roomtype = subRes.getRoomType().getId();
		
		List<Room> obj = new PopupLogic(req,resp).LoadRoomWithCache(hotelId, roomtype);
		
		for(SubReservation s:subResFromDB){
			if(s.isSellRoom() && s.getSellRoomDate() == Util.addDays(s.getDateTo(), -1))
				continue;
			
			for(int i=0;i<obj.size();i++)
				if(obj.get(i).getId() == s.getRoom().getId() && s.getRoom().getId() != room)
				{
					obj.remove(i);
					break;
				}
		}
		
		int i = 0;
		for(i=0;i<obj.size();i++)
			if(obj.get(i).getId() == room)
				break;
		if(i < (obj.size() - 1))
			return obj.get(i+1);
		else
			return obj.get(0);
	}
	
	public Room AutoMoveRoom(SubReservation subRes){
		Room nextRoom = GetNextAvaliableNextRoom(subRes);
		if(subRes.getId() > 0){
			subRes.setRoom(nextRoom);
			subRes.setRoomType(nextRoom.getRoomtype());
			datastore.put(subRes.getEntity());
			return nextRoom;
		}else{
			Reservation r = this.GetReservation(subRes.getParentId());
			r.setRoom(nextRoom);
			r.setRoomType(nextRoom.getRoomtype());
			datastore.put(r.getEntity());
			return nextRoom;
		}
	}
	public Room AutoMoveRoomWithSellRoom(SubReservation subRes){
		Room nextRoom = GetNextAvaliableNextRoomWithSellRoom(subRes);
		if(subRes.getId() > 0){
			subRes.setRoom(nextRoom);
			subRes.setRoomType(nextRoom.getRoomtype());
			datastore.put(subRes.getEntity());
			return nextRoom;
		}else{
			Reservation r = this.GetReservation(subRes.getParentId());
			r.setRoom(nextRoom);
			r.setRoomType(nextRoom.getRoomtype());
			datastore.put(r.getEntity());
			return nextRoom;
		}
	}
	
	//??
	public Room AutoMoveRoom(SubReservation subRes,long id)
	{
		Room nextRoom = GetNextAvaliableNextRoom(subRes);
		RoomLogic roomLogic = new RoomLogic(req,resp);
		Room roomSwap = roomLogic.GetRoom(id);
		if(subRes.getId() > 0)
		{
			SubReservationLogic subResvLogic = new SubReservationLogic(req,resp);
			SubReservation sub = subResvLogic.GetSubReservation(subRes.getId());
			Room rsRoom;
			if(sub.getRoom().getId() != nextRoom.getId())
				rsRoom = nextRoom;
			else
				rsRoom = roomSwap;
			sub.setRoom(rsRoom);
			sub.setRoomType(rsRoom.getRoomtype());
			datastore.put(sub.getEntity());
			return rsRoom;
		}
		else
		{
			Reservation r = this.GetReservation(subRes.getParentId());
			Room rsRoom;
			if(r.getRoom().getId() != nextRoom.getId())
				rsRoom = nextRoom;
			else
				rsRoom = roomSwap;
			r.setRoom(rsRoom);
			r.setRoomType(rsRoom.getRoomtype());
			datastore.put(r.getEntity());
			return rsRoom;
		}
	}
	public List<Reservation> GetRoomUsedBetweenCheckin(long hotelId,
			Date Maxdate, long roomtype, long roomId) {
		Query q = new Query(EntityName.Reservation);
		Filter filterhotelId = new FilterPredicate("hotelId",
				FilterOperator.EQUAL, hotelId);
		Filter filterDate = new FilterPredicate("date",
				FilterOperator.LESS_THAN_OR_EQUAL, Maxdate);
		Filter filterroomType = new FilterPredicate("roomType",
				FilterOperator.EQUAL, String.valueOf(roomtype));
		
		Filter filterroomId = new FilterPredicate("roomId",
				FilterOperator.EQUAL, String.valueOf(roomId));
		Filter filter = CompositeFilterOperator.and(filterhotelId, filterDate,
				filterroomType, filterroomId);
		q.setFilter(filter).addSort("date", SortDirection.DESCENDING);
		return GetList(datastore.prepare(q).asList(
				FetchOptions.Builder.withLimit(1)));
	}
	public List<Reservation> GetRoomUsedBetweenCheckout(long hotelId,
			Date Maxdate, long roomtype, long roomId) {
		Query q = new Query(EntityName.Reservation);
		Filter filterhotelId = new FilterPredicate("hotelId",
				FilterOperator.EQUAL, hotelId);
		Filter filterDate = new FilterPredicate("date",
				FilterOperator.GREATER_THAN, Maxdate);
		Filter filterroomType = new FilterPredicate("roomType",
				FilterOperator.EQUAL, String.valueOf(roomtype));
		Filter filteravaliable = new FilterPredicate("avaliable",
				FilterOperator.EQUAL, true);
		
		Filter filterroomId = new FilterPredicate("roomId",
				FilterOperator.EQUAL, String.valueOf(roomId));
		Filter filter = CompositeFilterOperator.and(filterhotelId, filterDate,
				filterroomType, filterroomId ,filteravaliable);
		q.setFilter(filter).addSort("date", SortDirection.ASCENDING);

		return GetList(datastore.prepare(q).asList(
				FetchOptions.Builder.withLimit(1)));
	}
	public Reservation GetReservation(Entity entity) {
		Reservation item = new Reservation();
		item.setEntity(entity);
		return item;
	}
	public List<Reservation> GetReservationInGroup(long groupId) {
		List<Reservation> list = new ArrayList<Reservation>();
		Group g = GetGroup(groupId);
		String[] resId = g.getListResvString().split(",");
		for(int i = 0;i<resId.length;i++){
			list.add(GetReservation(Long.parseLong(resId[i].trim())));	
		}
		return list;
	}
	public List<Reservation> GetList(List<Entity> entities) {
		List<Reservation> list = new ArrayList<Reservation>();
		if(entities != null)
		for (Entity e : entities) {
			Reservation a = new Reservation();
			a.setEntity(e);
			list.add(a);
		}
		return list;
	}
	public List<SubReservation> GetSubReservationList(List<Entity> entities) {
		List<SubReservation> list = new ArrayList<SubReservation>();
		if(entities != null)
		for (Entity e : entities) {
			SubReservation a = new SubReservation();
			a.setEntity(e);
			list.add(a);
		}
		return list;
	}
	public List<Reservation> GetReservation(Date resDate, String roomId) {
		Query q = new Query(EntityName.Reservation);

		Filter filterresDate = new FilterPredicate("date",
				FilterOperator.EQUAL, resDate);

		Filter filterroomId = new FilterPredicate("roomId",
				FilterOperator.EQUAL, roomId);

		Filter filter = CompositeFilterOperator
				.and(filterresDate, filterroomId);

		q.setFilter(filter);

		return GetList(datastore.prepare(q).asList(
				FetchOptions.Builder.withDefaults()));
	}

	public boolean RemoveRes(long resId) {
		
		Reservation r = GetReservation(resId);
		List<SubReservation> s = r.getSubReservationList();
		
		for(SubReservation sub : s)
		{
			Key k = KeyFactory.createKey(EntityName.SubReservation, sub.getId());
			datastore.delete(k);
		}
		
		Key key = KeyFactory.createKey(EntityName.Reservation, resId);
		datastore.delete(key);
		return true;
	}

	public List<ReservationStatus> GetReservationStatus(long hotelId) {
		Query q = new Query(EntityName.ReservationStatus);

		Filter filter = new FilterPredicate("hotelId", FilterOperator.EQUAL,
				hotelId);

		q.setFilter(filter);
		return GetListStatus(datastore.prepare(q).asList(
				FetchOptions.Builder.withDefaults()));
	}
	public List<ReservationStatus> GetListStatus(List<Entity> entities) {
		List<ReservationStatus> list = new ArrayList<ReservationStatus>();
		if(entities!=null)
		for (Entity e : entities) {
			ReservationStatus a = new ReservationStatus();
			a.setEntity(e);
			list.add(a);
		}
		return list;
	}
	// ////////////////////// == PAO == ///////////////////////////
	public Reservation EditTaskList(long hotelId, long resId, String data_task)
			throws EntityNotFoundException, ParseException {
		Reservation rsv = GetReservation(resId);
		String oldData_task = rsv.getTaskListString();
		if (oldData_task != null) {
			rsv.setTaskListString(oldData_task + ',' + data_task);
		} else {
			rsv.setTaskListString(data_task);
		}
		Key k = datastore.put(rsv.getEntity());
		rsv.setId(k.getId());
		rsv.setKey(k);
		return rsv;
	}
	public Reservation GetIdTaskList(long res_id) {
		Key key = KeyFactory.createKey(EntityName.Reservation, res_id);
		try {
			Entity lang = datastore.get(key);
			Reservation c = new Reservation();
			c.setEntity(lang);
			return c;
		} catch (EntityNotFoundException e) {
			return null;
		}
	}
	public Group EditDetailGroup(long hotelId, long groupId, Date date,
			long extrabed, String reason, String source, long span)
			throws EntityNotFoundException, ParseException {
		Group g = GetGroup(groupId);
		g.setDate(date);
		g.setExtrabed(extrabed);
		g.setObjective(reason);
		g.setSourcesString(source);
		g.setSpan(span);
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);

		return g;
	}
	public Group EditGroupRoomManage(long hotelId, long groupId,String resId,String agencyId)
			throws EntityNotFoundException, ParseException {
		Group g = GetGroup(groupId);
		g.setListResvString(resId);
		g.setAgencyIdString(agencyId);
		String[] resArray = resId.split(",");
		if(!resId.equals("0")){
			Reservation r = GetReservation(Long.parseLong(resArray[0]));
			g.setRoomtypeString(r.getRoomTypeString());
			for(int i =0; i<resArray.length;i++)
			{
				EditReservationRoomManage(resArray[i],groupId);
			}
		}
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);

		return g;
	}
	public Group RemoveFromGroupRoomManage(long hotelId, long groupId,String resId)
			throws EntityNotFoundException, ParseException {
		Group g = GetGroup(groupId);
		String[] arrayResList = g.getListResvString().split(",");
		String resIdNewSet ="";
		ArrayList<String> arrayResListGroup = new ArrayList<String>();
		// add resid in array
		for(int i =0;i<arrayResList.length;i++){
			arrayResListGroup.add(arrayResList[i].trim());
		}
		String[] arrayResListRemove = resId.split(",");
		// check resid for remove resid in array
		for(int i =0;i<arrayResList.length;i++){
			String GroupResId = arrayResList[i].trim();
			for(int j = 0;j<arrayResListRemove.length;j++){
				String removeResId = arrayResListRemove[j].trim();
				if(GroupResId.equals(removeResId)){
					arrayResListGroup.remove(GroupResId);
					RemoveReservationRoomMange(GroupResId);
				}
			}
		}
		if(arrayResListGroup.size()!=0){
			for(int i = 0;i<arrayResListGroup.size();i++){
				resIdNewSet += arrayResListGroup.get(i) + ",";
			}
			g.setListResvString(resIdNewSet.substring(0, resIdNewSet.length()-1));	
		}
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);
		return g;
	}
	public Reservation RemoveReservationRoomMange(String resId)
			throws EntityNotFoundException, ParseException {
		Reservation r = GetReservation(Long.parseLong(resId));
		r.setGroupIdString("0");
		r.setGroupIdNumber(0);
	//	g.setGroupIdString(String.valueOf(groupId));
		//g.setGroupIdNumber(groupId);
		Key k = datastore.put(r.getEntity());
		r.setId(k.getId());
		r.setKey(k);
		return r;
	}
	public Group AddFromGroupRoomManage(long hotelId, long groupId,String resId)
			throws EntityNotFoundException, ParseException {
		Group g = GetGroup(groupId);
		String ResListAdd = resId;
		String ResListGroup = g.getListResvString();
		String ResListAddGroup = ResListGroup+","+ResListAdd;
		g.setListResvString(ResListAddGroup);
		String[] arrayResListRemove = resId.split(",");
		for(int j = 0;j<arrayResListRemove.length;j++){
			String removeResId = arrayResListRemove[j].trim();
			AddGroupReservationRoomMange(removeResId,String.valueOf(groupId));
		}
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);
		return g;
	}
	public Reservation AddGroupReservationRoomMange(String resId,String GroupId)
			throws EntityNotFoundException, ParseException {
		Reservation r = GetReservation(Long.parseLong(resId));
		r.setGroupIdString(GroupId);
		r.setGroupIdNumber(Long.parseLong(GroupId));
		Key k = datastore.put(r.getEntity());
		r.setId(k.getId());
		r.setKey(k);
		return r;
	}
	public Reservation EditReservationRoomManage(String resId,long groupId)
			throws EntityNotFoundException, ParseException {
		Reservation g = GetReservation(Long.parseLong(resId));
		g.setGroupIdString(String.valueOf(groupId));
		g.setGroupIdNumber(groupId);
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);
		return g;
	}
	public Group EditChargeGroup(long hotelId, long groupId, String chargeId, boolean isRoomsSharge)
			throws EntityNotFoundException, ParseException {
		Group g = GetGroup(groupId);
		if(isRoomsSharge)
		{
			if(g.getChargeListString()!=null)
			{
				g.setChargeListString(g.getChargeListString()+","+chargeId);
			}else
			{
				g.setChargeListString(chargeId);
			}
		}else
		{
			if(g.getOtherChargeString()!=null)
			{
				g.setOtherChargeString(g.getOtherChargeString()+","+chargeId);
			}else
			{
				g.setOtherChargeString(chargeId);
			}
		}
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);

		return g;
	}
	
	public Reservation EditChargeListString( long resId, String chargeId)
			throws EntityNotFoundException, ParseException {
		Reservation g = GetReservation(resId);
		g.setChargeListString(chargeId);
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);

		return g;
	}
	
	public Reservation EditDetailReservation(long hotelId, long resId,
			Date date, long extrabed, String reason, String source, long span)
			throws EntityNotFoundException, ParseException {
		Reservation g = GetReservation(resId);
		g.setDate(date);
		g.setExtrabed(extrabed);
		if(source!=null && source != "")
			g.setSourcesString(source);
		g.setSpan(span);
		g.setObjective(reason);
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);

		return g;
	}
	public Reservation EditDetailReservation(long hotelId, long resId,
			Date date, long span)
			throws EntityNotFoundException, ParseException {
		Reservation g = GetReservation(resId);
		g.setDate(date);
		g.setSpan(span);
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);

		return g;
	}
	public Group EditCreditCard(long groupId, String creditCard)
			throws EntityNotFoundException, ParseException {
		Group g = GetGroup(groupId);
		g.setCreditString(creditCard);
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);

		return g;
	}
	public Group EditDateCheckinGroup(long groupId, Date date)
			throws EntityNotFoundException, ParseException {
		Group g = GetGroup(groupId);
		g.setDate(date);
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);

		return g;
	}
	public Reservation EditCreditCard2Res(long resId, String creditCard)
			throws EntityNotFoundException, ParseException {
		Reservation g = GetReservation(resId);
		g.setCreditString(creditCard);
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);

		return g;
	}
	public Group EditTaskListGroup(long hotelId, long group_id, String data_task)
			throws EntityNotFoundException, ParseException {
		Group rsv = GetReservationGroup(group_id);
		String oldData_task = rsv.getTaskListString();
		if (oldData_task != null) {
			rsv.setTaskListString(oldData_task + ',' + data_task);
		} else {
			rsv.setTaskListString(data_task);
		}
		Key k = datastore.put(rsv.getEntity());
		rsv.setId(k.getId());
		rsv.setKey(k);
		return rsv;
	}
	public Group GetReservationGroup(long id) {
		Key key = KeyFactory.createKey(EntityName.Group, id);
		try {
			Entity lang = datastore.get(key);
			Group c = new Group();
			c.setEntity(lang);
			return c;
		} catch (EntityNotFoundException e) {
			return null;
		}
	}
	public Group GetIdTaskListGroup(long group_id) {
		Key key = KeyFactory.createKey(EntityName.Group, group_id);
		try {
			Entity lang = datastore.get(key);
			Group c = new Group();
			c.setEntity(lang);
			return c;
		} catch (EntityNotFoundException e) {
			return null;
		}
	}
	public void EditTravelGroup(long hotelId, long group_id, String travelId,
			String resId) throws EntityNotFoundException, ParseException {
		if (group_id != 0) {
			Group rsv = GetGroup(group_id);
			rsv.setTravelString(travelId);
			Key k = datastore.put(rsv.getEntity());
			rsv.setId(k.getId());
			rsv.setKey(k);
		} else {
			Reservation res = GetReservation(Long.parseLong(resId));
			res.setTravelString(travelId);
			Key k = datastore.put(res.getEntity());
			res.setId(k.getId());
			res.setKey(k);
		}
	}

	public Reservation EditGuest(long resvId, String guestString)
			throws EntityNotFoundException, ParseException {
		Reservation g = GetReservation(resvId);
		g.setGuestString(guestString);
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);

		return g;
	}
	public Reservation EditRoomtypeS(long resvId, String roomtypeString)
			throws EntityNotFoundException, ParseException {
		Reservation g = GetReservation(resvId);
		g.setRoomTypeString(roomtypeString);
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);

		return g;
	}
	public Reservation EditRoomS(long resvId, String roomString)
			throws EntityNotFoundException, ParseException {
		Reservation g = GetReservation(resvId);
		g.setRoomString(roomString);
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);

		return g;
	}
	public Reservation EditRoomS2(long resvId, String roomString)
			throws EntityNotFoundException, ParseException {
		Reservation g = GetReservation(resvId);
		g.setRoomString(roomString);
		g.setAssign(true);
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);

		return g;
	}
	public Reservation EditRoomStatusS(long resvId, String roomStatusString)
			throws EntityNotFoundException, ParseException {
		Reservation g = GetReservation(resvId);
		g.setReservationStatusString(roomStatusString);
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);

		return g;
	}
	public Reservation EditPackageS(long resvId, String packageString)
			throws EntityNotFoundException, ParseException {
		Reservation g = GetReservation(resvId);
		g.setPackageByDateString(packageString);
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);

		return g;
	}
	public Group EditResList(long groupId, String listResvString)
			throws EntityNotFoundException, ParseException {
		Group g = GetGroup(groupId);
		g.setListResvString(listResvString);
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);

		return g;
	}
	public Group EditPaymentList(long groupId, String listPaymentString)
			throws EntityNotFoundException, ParseException {
		Group g = GetGroup(groupId);
		g.setPaymentListString(listPaymentString);
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);

		return g;
	}
	public Reservation EditResPaymentList(long resvId, String listPaymentString)
			throws EntityNotFoundException, ParseException {
		Reservation g = GetReservation(resvId);
		g.setPaymentListString(listPaymentString);
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);

		return g;
	}
	public Reservation AddResInGroup(String roomtypeNew, String roomNew,
			String guestIdNew,String adultNew, String childNew,
			String roomStatusNew, String dateNew, String spanNew,
			String packageNew, String priceNew, String groupIdNew, long hotelId, String agencyId)
			throws EntityNotFoundException, ParseException {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
				Locale.ENGLISH);

		Reservation t = new Reservation();
		t.setHotelId(hotelId);
		t.setDisplayId(GetMaxResvDisplayId(hotelId)+1);
		t.setAgencyIdString(agencyId);
		t.setRoomTypeString(roomtypeNew);
		t.setRoomString(roomNew);
		t.setGroupIdString(groupIdNew);
		t.setGroupIdNumber(Long.parseLong(groupIdNew));
		t.setAssign(true);
		t.setOrder(1);
		t.setPaymentListString("");
		t.setGuestString(guestIdNew);
		t.setAvaliable(true);
		t.setStatus(true);
		t.setCreditString("0");
		t.setAdult(Long.parseLong(adultNew));
		t.setChild(Long.parseLong(childNew));
		t.setReservationStatusString(roomStatusNew);
		t.setDate(formatter.parse(dateNew));
		t.setSpan(Long.parseLong(spanNew));
		PackageByDate packagebydate = new PackageLogic(req,resp)
		.AddPackageByDate(packageNew, formatter.parse(dateNew), 
				Util.addDays(formatter.parse(dateNew), Long.parseLong(spanNew)));
		t.setPackageByDateString(String.valueOf(packagebydate.getId()));
		ChargeLogic cLogic = new ChargeLogic(req,resp);
		TaxLogic taxLogic = new TaxLogic(req,resp);
		String chargeList = "";
		for(int x = 0;x<Long.valueOf(spanNew);x++){
			HashMap<String,Double> calTax = taxLogic.CalRoomTax(hotelId,Long.parseLong(priceNew)/Long.parseLong(spanNew),x);
			Charge c = cLogic.AddCharge(hotelId, "Room Rate",0,
					calTax.get("costIncludeTax"), Util.addDays(formatter.parse(dateNew), x), (double) 0, "0", calTax.get("tax"), false, true,true,0,null,null);
			if(x == Long.valueOf(spanNew)-1){
				chargeList += String.valueOf(c.getId()); 
			}else{
				chargeList += String.valueOf(c.getId())+","; 
			}

		}
		t.setChargeListString(chargeList);
		Key k = datastore.put(t.getEntity());
		t.setId(k.getId());
		t.setKey(k);

		return t;
	}
	public Reservation EditAdultS(long resvId, long adult)
			throws EntityNotFoundException, ParseException {
		Reservation g = GetReservation(resvId);
		long stdocc = g.getRoomType().getStandardOccupancy();
		long child = g.getChild();
		g.setAdult(adult);
		g.setExtrabed((adult+child > stdocc)? adult+child-stdocc:0);
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);

		return g;
	}
	public Reservation EditChildS(long resvId, long child)
			throws EntityNotFoundException, ParseException {
		Reservation g = GetReservation(resvId);
		long stdocc = g.getRoomType().getStandardOccupancy();
		long adult = g.getAdult();
		g.setChild(child);
		g.setExtrabed((adult+child > stdocc)? adult+child-stdocc:0);
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);

		return g;
	}
	public Reservation EditSpanS(long resvId, String span)
			throws EntityNotFoundException, ParseException {
		Reservation g = GetReservation(resvId);
		g.setSpan(Long.parseLong(span));
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);

		return g;
	}
	public Reservation EditDateS(long resvId, Date date)
			throws EntityNotFoundException, ParseException {
		Reservation g = GetReservation(resvId);
		g.setDate(date);
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);

		return g;
	}

	public Reservation EditAdditionalGuest(long hotelId,long reservationId, String guestId)
			throws EntityNotFoundException, ParseException {
		Reservation rsv = GetReservation(reservationId);
		String oldData_task = rsv.getAdditionalGuestString();
		if(oldData_task != null){
			if(rsv.getAdult()+rsv.getChild() < rsv.getAdditionalGuestString().split(",").length+1){
				
				rsv = EditAdultS(reservationId,rsv.getAdult()+1);
			}
		}

		long guestAmount = rsv.getAdult()+rsv.getChild();
		long occStandard = rsv.getRoomType().getStandardOccupancy();
		if(guestAmount > occStandard){
			if(guestAmount - occStandard < rsv.getRoomType().getExtraBedAllowed()){
				rsv.setExtrabed(guestAmount - occStandard);
			}else{
				rsv.setExtrabed(rsv.getRoomType().getExtraBedAllowed());
			}
			
		}
		if (oldData_task != null && !guestId.equals("0")) {
			rsv.setAdditionalGuestString(oldData_task + ',' + guestId);
		} else {
			if(!guestId.equals("0")){
				rsv.setAdditionalGuestString(guestId);
			}
		}
		Key k = datastore.put(rsv.getEntity());
		rsv.setId(k.getId());
		rsv.setKey(k);
		
		List<SubReservation> sublist = rsv.getSubReservationList();
		if(sublist.size() ==0){
			SubReservation aa = new SubReservation();
			aa.CloneReservation(rsv);
			sublist.add(aa);
		}
		List<Charge> chargelist = rsv.getChargeList();
		Date mindate = chargelist.get(0).getChargeDate();
		Date maxdate = chargelist.get(0).getChargeDate();
		for(int i=0;i<chargelist.size();i++){
			if(chargelist.get(i).getChargeDate().before(mindate)){
				mindate = chargelist.get(i).getChargeDate();
			}
			if(chargelist.get(i).getChargeDate().after(maxdate)){
				maxdate = chargelist.get(i).getChargeDate();
			}
		}
		
		List<SubReservation> subResvlist = rsv.getSubReservationList();
		if(subResvlist.size() == 0){
			subResvlist = new ArrayList<SubReservation>();
			SubReservation sub = new SubReservation();
			sub.CloneReservation(rsv);
			subResvlist.add(sub);
		}
			
		
		new ChargeLogic(req,resp).CalCharge(hotelId, subResvlist, 
				rsv.getPackageByDate(),mindate,maxdate);
			
		return rsv;
	}

	public Reservation DeleteAdditionalGuest(long hotelId,long reservationId,
			String guestIdString) throws EntityNotFoundException,
			ParseException {		
		Reservation rsv = GetReservation(reservationId);
		List<Guest> guests = rsv.getAdditionalGuest();
		String[] guestArray = guestIdString.split(",");
		long removeGuest =0;
		for(String gIdString : guestArray)
		{
			long id = Long.parseLong(gIdString);
			if(id == 0)
			{
				boolean a = DelguestsAmount(reservationId,1);
				if(a){
					continue;
				}
			}
			for(Guest g : guests)
				if(id == g.getId())
				{
					guests.remove(g);
					removeGuest++;
					break;
				}
		}
		rsv = GetReservation(reservationId);
		if(guests.size() != (rsv.getChild()+rsv.getAdult()))
		{
			long delAmount =removeGuest;
			DelguestsAmount(reservationId,delAmount);
		}
		if(guests.size()!=0){
		rsv.setAdditionalGuest(guests);
		rsv.setGuest((guests.size() > 0)? guests.get(0) : null);
		}else
		{
			rsv.setAdditionalGuestString(null);
			rsv.setGuestString("0");
		}
		//rsv.setAdult(guests.size() - rsv.getChild());
		//rsv.setAdult(guests.size());
		long occStandard = rsv.getRoomType().getStandardOccupancy();
		if(guests.size() < occStandard){
			rsv.setExtrabed(0);
		}else{
			if(guests.size() - occStandard < rsv.getRoomType().getExtraBedAllowed()){
				rsv.setExtrabed(guests.size() - occStandard);
			}else{
				rsv.setExtrabed(rsv.getRoomType().getExtraBedAllowed());
			}
		}
		
		// end ma edit , thx
		Key k = datastore.put(rsv.getEntity());
		rsv.setId(k.getId());
		rsv.setKey(k);
		
		List<SubReservation> sublist = rsv.getSubReservationList();
		if(sublist.size() ==0){
			SubReservation aa = new SubReservation();
			aa.CloneReservation(rsv);
			sublist.add(aa);
		}
		List<Charge> chargelist = rsv.getChargeList();
		Date mindate = chargelist.get(0).getChargeDate();
		Date maxdate = chargelist.get(0).getChargeDate();
		for(int i=0;i<chargelist.size();i++){
			if(chargelist.get(i).getChargeDate().before(mindate)){
				mindate = chargelist.get(i).getChargeDate();
			}
			if(chargelist.get(i).getChargeDate().after(maxdate)){
				maxdate = chargelist.get(i).getChargeDate();
			}
		}
		
		List<SubReservation> subResvList = rsv.getSubReservationList();
		if(subResvList == null || subResvList.size() == 0)
		{
			SubReservation subResv = new SubReservation();
			subResv.CloneReservation(rsv);
			subResvList.add(subResv);
		}
		
		new ChargeLogic(req,resp).CalCharge(hotelId, subResvList, 
				rsv.getPackageByDate(),mindate,maxdate);
		
		return rsv;
	}

	public boolean DelguestsAmount(long resId,long Amount) throws EntityNotFoundException
	{
		Reservation r = GetReservation(resId);
		long b=r.getChild();
		long c=r.getAdult();
		for(int i=0;i<Amount;i++){
			if((b+c)>1){
				if(b!=0)
				{
				 b-=1;
				}
				else
				{
					if(c!=0)
					{
						c-=1;
					}
				}
			}
		}
		r.setChild(b);
		r.setAdult(c);
		Key k = datastore.put(r.getEntity());
		r.setId(k.getId());
		r.setKey(k);
		return true;
	}
	
	public Reservation BackListReservation(long id)
			throws EntityNotFoundException {
		Reservation t = GetReservation(id);
		t.setAvaliable(false);
		t.setStatus(true);

		Key k = datastore.put(t.getEntity());
		t.setId(k.getId());
		t.setKey(k);

		return t;
	}
	public ReservationStatus GetReservationStatusCheck(long id) {
		Key key = KeyFactory.createKey(EntityName.ReservationStatus, id);
		try {
			Entity lang = datastore.get(key);
			ReservationStatus c = new ReservationStatus();
			c.setEntity(lang);
			return c;
		} catch (EntityNotFoundException e) {
			return null;
		}
	}
	public String LoadBookingDetail(long groupId,boolean checkStatus)
	{
		String pd = null;
		String sp = null;
		Group g = GetGroup(groupId);
		List<Reservation> resArray = g.getListResv();
		int countRes =0;
		int countCkin=0;
		int countCkout=0;
		int countTemp=0;
		for(Reservation r : resArray)
		{
			String resCheck =r.getReservationStatus().getTitle();
			if(resCheck.equals("Reserved Rooms"))
			{
				countRes++;
			}
			if(resCheck.equals("Checked-in Rooms"))
			{
				countCkin++;	
			}
			 if(resCheck.equals("Checked-out Rooms"))
			{
				countCkout++;
			}
			 if(resCheck.equals("Temp Rooms"))
			{
				countTemp++;
			}
			
		}
		
		if(countRes!= 0 ||countTemp!= 0 )
		{
			if(countRes >= countTemp){
			if(resArray.size() == countRes )
			{
				pd="Reserved Rooms";	
			}else
			{
				pd="Some Reserved Rooms";
			}
			sp="Reserved Rooms";
			}else
			{
				if(resArray.size() == countTemp )
				{
					pd="Temp Rooms";
				}else
				{
					pd="Some Temp Rooms";
				}
				sp="Temp Rooms";
			}
		}
		if( countCkin!= 0 )
		{
			if(resArray.size() == countCkin )
			{
				pd="Checked-in Rooms";
			}else
			{
				pd="Some Checked-in Rooms";
			}
			sp="Checked-in Rooms";
		}
		if(countCkout != 0 )
		{
			if(resArray.size() == countCkout )
			{
				pd="Checked-out Rooms";	
			}else
			{
				pd="Some Checked-out Rooms";
			}
			sp="Checked-out Rooms";
		}
		if(checkStatus)return sp;
		else return pd;
		
	
	}
	
	public PaymentData LoadSingleBookingDetail(long resId)
	{
	
		PaymentData pd = new PaymentData();
		
		Reservation reserved = GetReservation(resId); 
		
		if(reserved.getGroupIdNumber()!=0){
		pd.setGroupId(String.valueOf(reserved.getGroupIdNumber()));
		}else
		{
			pd.setResId(String.valueOf(reserved.getId()));	
		}
		
		
		Agency a= new AgencyLogic(req,resp).GetAgency(Long.parseLong(reserved.getAgencyIdString()));
		pd.setCompany(a.getAgency());
		if(!reserved.getGroupIdString().equals("0"))
		{
			Group g = GetGroup(Long.parseLong(reserved.getGroupIdString().trim()));
			pd.setGroupOwner(g.getGuest().getFirstName()+" "+g.getGuest().getLastName());
			pd.setGroupRoomOwner(reserved.getGuest().getFirstName()+" "+reserved.getGuest().getLastName());
			
		}
		else
		{
			pd.setGroupOwner(reserved.getGuest().getFirstName()+" "+reserved.getGuest().getLastName());
		}

		pd.setOwnerGroupId(String.valueOf(reserved.getGuest().getId()));
		pd.setIdNumber(reserved.getGuest().getIdNumber());
		if(!reserved.getGroupIdString().equals("0"))
		{
			Group g = GetGroup(Long.parseLong(reserved.getGroupIdString().trim())); 
			pd.setAddress(g.getGuest().getAddressLine1());
			pd.setTel(g.getGuest().getPhone());
			pd.setRatePackage(g.getPriceRate().getName());
		}
		else
		{
			pd.setAddress(reserved.getGuest().getAddressLine1());
			pd.setTel(reserved.getGuest().getPhone());
			List<PackageByDate> pbd = reserved.getPackageByDate();
			String packageName = "";
			for(int x=0;x<pbd.size();x++){
				packageName += pbd.get(x).getPackages().getName()+",";
			}
			pd.setRatePackage(packageName.substring(0, packageName.length()-1));
		}
		
		pd.setResStatus(reserved.getReservationStatus().getTitle());
		
		List<String>roomNameAray = new ArrayList<String>();
		
		
			pd.setResId(String.valueOf(reserved.getId()));
			roomNameAray.add(reserved.getRoom().getRoomName());
		
			
		pd.setRoomname(roomNameAray);
		pd.setRoomType(reserved.getRoomType().getShortName());
		pd.setNight(reserved.getSpan());
		pd.setRoomAmount(1);
		pd.setAdultAmount(reserved.getAdult());
		pd.setChildrenAmount(reserved.getChild());
		pd.setStartDate(reserved.getDate());
		pd.setStopDate(reserved.getDateTo());
		
		return pd;
	
	}
	public Reservation EditReservationCharge(long hotelId, long resId,
			String data , boolean isRoomsSharge)
			throws EntityNotFoundException, ParseException {
		Reservation rsv = GetReservation(resId);
		if(isRoomsSharge)
		{
			if(rsv.getChargeListString()!=null)
			{
				rsv.setChargeListString(rsv.getChargeListString()+","+data);
			}else
			{
				rsv.setChargeListString(data);
			}
		}else
		{
			if(rsv.getOtherChargeString()!=null)
			{
				rsv.setOtherChargeString(rsv.getOtherChargeString()+","+data);
			}else
			{
				rsv.setOtherChargeString(data);
			}
		}

		Key k = datastore.put(rsv.getEntity());
		rsv.setId(k.getId());
		rsv.setKey(k);

		return rsv;
	}
	public ReservationStatus addReservationStatus(long hotelId, String title, String color)
			throws EntityNotFoundException, ParseException {
		ReservationStatus rsvs = new ReservationStatus();
		rsvs.setTitle(title);
		rsvs.setColor(color);
		rsvs.setHotelId(hotelId);
		Key k = datastore.put(rsvs.getEntity());
		rsvs.setId(k.getId());
		rsvs.setKey(k);

		return rsvs;
	}
	
	public Reservation AssignRoom(long resId, boolean assign,String roomString) throws EntityNotFoundException, ParseException{
		Reservation rsv = GetReservation(resId);
		rsv.setAssign(assign);
		rsv.setRoomString(roomString);
		Key k = datastore.put(rsv.getEntity());
		rsv.setId(k.getId());
		rsv.setKey(k);
		return rsv;
	}
	public Reservation EditAgency(long resId, long agencyId) throws EntityNotFoundException, ParseException{
		Reservation rsv = GetReservation(resId);
		rsv.setAgencyIdString(String.valueOf(agencyId));
		Key k = datastore.put(rsv.getEntity());
		rsv.setId(k.getId());
		rsv.setKey(k);
		return rsv;
	}
	
	public Group EditAgencyGroup(long groupId, long agencyId) throws EntityNotFoundException, ParseException{
		Group rsv = GetGroup(groupId);
		rsv.setAgencyIdString(String.valueOf(agencyId));
		Key k = datastore.put(rsv.getEntity());
		rsv.setId(k.getId());
		rsv.setKey(k);
		return rsv;
	}
	public Reservation UpdateReservation(Reservation rsv)
	{
		Key key = datastore.put(rsv.getEntity());
		rsv.setId(key.getId());
		rsv.setKey(key);
		return rsv;
	}
	
	public Reservation EditSubResString(long resId,String subres) throws EntityNotFoundException, ParseException{
		Reservation rsv = GetReservation(resId);
		rsv.setSubReservationListString(subres);
		Key k = datastore.put(rsv.getEntity());
		rsv.setId(k.getId());
		rsv.setKey(k);
		return rsv;
	}
	
	public String EditPackageByDate(List<PackageByDate> pbd ,Date newFrom, Date newTo) throws EntityNotFoundException{
		Date from = pbd.get(0).getDateFrom();
		Date to = pbd.get(0).getDateTo();
		int from_index = 0;
		int to_index = 0;
		
		for(int i=0;i<pbd.size();i++){
			if(pbd.get(i).getDateFrom().before(from)){
				from = pbd.get(i).getDateFrom();
				from_index = i;
			}
		}
		for(int i=0;i<pbd.size();i++){
			if(pbd.get(i).getDateTo().after(to)){
				to = pbd.get(i).getDateTo();
				to_index = i;
			}
		}
		if(newFrom.before(from)){
			//edit
			PackageByDate xx  = new PackageLogic(req,resp).EditPackageByDate(pbd.get(from_index).getId(), newFrom, 
					pbd.get(from_index).getDateTo(), pbd.get(from_index).getPackageString());
			pbd.set(from_index, xx);
		}
		if(newTo.after(to)){
			//edit
			PackageByDate xx  = new PackageLogic(req,resp).EditPackageByDate(pbd.get(to_index).getId(), pbd.get(to_index).getDateFrom(), 
					newTo, pbd.get(to_index).getPackageString());
			pbd.set(to_index, xx);
		}
		for(int i=0;i<pbd.size();i++){
			Date df = pbd.get(i).getDateFrom();
			Date dt = pbd.get(i).getDateTo();
			long id = pbd.get(i).getId();
			String packageString = pbd.get(i).getPackageString();
			if(dt.before(newFrom) || (dt.equals(newFrom) && pbd.size()>1)){
				//delete entity
				DeletePackageByDate(pbd.get(i).getId());
				//delete pbd
				pbd.remove(i);
				i--;
				continue;
			}
			if(df.after(newTo) || (df.equals(newTo) && pbd.size()>1)){
				//delete
				DeletePackageByDate(pbd.get(i).getId());
				//delete pbd
				pbd.remove(i);
				i--;
				continue;
			}
			if(newFrom.after(df) && newFrom.before(dt)){	
				//edit
				pbd.set(i, new PackageLogic(req,resp).EditPackageByDate(id, newFrom, dt, packageString));
				df = newFrom;
			}
			if(newTo.after(df) && newTo.before(dt)){
				//edit
				pbd.set(i, new PackageLogic(req,resp).EditPackageByDate(id, df, newTo, packageString));
			}
		}
		String pbdString = "";
		for(int i=0;i<pbd.size();i++){
			pbdString += pbd.get(i).getId()+",";
		}
		
		return pbdString.substring(0, pbdString.length()-1);
	}
	
	public void DeletePackageByDate(long packagebydateId){
		Key key = KeyFactory.createKey(EntityName.PackageByDate, packagebydateId);
		datastore.delete(key);
	}
	
	public HashMap<String, Object> EditAboutDetailReservation(long hotelId,long resId,Date date,long extrabed,
			String reason,String source,long span) throws EntityNotFoundException, ParseException{
		Reservation res = GetReservation(resId);

		HashMap<String, Object> map = new HashMap<String, Object>();
		//no have subreservation
		if(res.getSubReservationList().size() == 0){
			long roomId = res.getRoom().getId();
			boolean canbeMove = true;
			List<SubReservation> sub = new ArrayList<SubReservation>();
			if(date.before(res.getDate()) || Util.addDays(date, span).after(res.getDateTo()))
			{
				sub = GetReservationWithinDateInSpecificRoom(hotelId, date, span, roomId);
				for(SubReservation s:sub)
					if(s.isAssign(this) || !CanBeChangeRoomWithSellRoom(s)) { canbeMove = false; break; }
				for(SubReservation s:sub)
					if(s.getParentId() == res.getId()) { sub.remove(s); break; }
			}
			if(canbeMove){
				for(SubReservation s:sub)
					AutoMoveRoomWithSellRoom(s);
			
			//edit in reservation
				res = EditDetailReservation(hotelId, resId, date,extrabed, reason, source, span);
				
				// edit package by date
				String pbdString = EditPackageByDate(res.getPackageByDate(), date, Util.addDays(date,span));
				res.setPackageByDateString(pbdString);
				res = UpdateReservation(res);
				
				List<SubReservation> sublist = res.getSubReservationList();
				if(sublist.size() ==0){
					SubReservation aa = new SubReservation();
					aa.CloneReservation(res);
					sublist.add(aa);
				}
				List<Charge> chargelist = res.getChargeList();
				Date mindate = chargelist.get(0).getChargeDate();
				Date maxdate = chargelist.get(0).getChargeDate();
				for(int i=0;i<chargelist.size();i++){
					if(chargelist.get(i).getChargeDate().before(mindate)){
						mindate = chargelist.get(i).getChargeDate();
					}
					if(chargelist.get(i).getChargeDate().after(maxdate)){
						maxdate = chargelist.get(i).getChargeDate();
					}
				}
				
				List<Charge> chargeList = new ChargeLogic(req,resp).CalCharge(hotelId, sublist, 
						res.getPackageByDate(),mindate,maxdate);
				
				map.put("SplitTable", sublist);
				map.put("PackageTable", res.getPackageByDate());
				map.put("ChargeList", chargeList);
			}
			return map;
		}else{
			//have subreservation
			List<SubReservation> subres = res.getSubReservationList();
			SubReservationLogic srLogic = new SubReservationLogic(req,resp);
			boolean canbeMove = true;
			List<SubReservation> sub = new ArrayList<SubReservation>();
			if(date.before(res.getDate()) || Util.addDays(date, span).after(res.getDateTo()))
			{
				SubReservation lastsub = srLogic.GetLastSubRes(subres);
				sub = GetReservationWithinDateInSpecificRoom(hotelId, date, span, lastsub.getRoom().getId());
				
				for(SubReservation s:sub)
					if(s.isAssign(this) || !CanBeChangeRoomWithSellRoom(s)) { canbeMove = false; break; }

				for(SubReservation s:sub)
					if(s.getParentId() == res.getId()) { sub.remove(s); break; }
			}
			if(canbeMove){
				for(SubReservation s:sub)
					AutoMoveRoomWithSellRoom(s);

				Date newFrom = date;
				Date newTo = Util.addDays(date, span);
				subres = srLogic.EditSubResvListDate(subres,newFrom,newTo);
				
				String subresstring = "";
				for(int d = 0;d<subres.size();d++){
					subresstring += subres.get(d).getId()+",";
				}
				res = EditSubResString(resId, subresstring.substring(0, subresstring.length() - 1));
				res = EditDetailReservation(hotelId, resId, date,extrabed, reason, source, span);
				
				// edit package by date
				String pbdString = EditPackageByDate(res.getPackageByDate(), date, Util.addDays(date,span));
				res.setPackageByDateString(pbdString);
				res = UpdateReservation(res);
				
				List<SubReservation> sublist = res.getSubReservationList();
				if(sublist.size() ==0){
					SubReservation aa = new SubReservation();
					aa.CloneReservation(res);
					sublist.add(aa);
				}
				List<Charge> chargelist = res.getChargeList();
				Date mindate = chargelist.get(0).getChargeDate();
				Date maxdate = chargelist.get(0).getChargeDate();
				for(int i=0;i<chargelist.size();i++){
					if(chargelist.get(i).getChargeDate().before(mindate)){
						mindate = chargelist.get(i).getChargeDate();
					}
					if(chargelist.get(i).getChargeDate().after(maxdate)){
						maxdate = chargelist.get(i).getChargeDate();
					}
				}
				
				List<Charge> chargeList = new ChargeLogic(req,resp).CalCharge(hotelId, subres, 
						res.getPackageByDate(),mindate,maxdate);
	
				map.put("SplitTable", subres);
				map.put("PackageTable", res.getPackageByDate());
				map.put("ChargeList", chargeList);
			}
			return map;
		}
	}
	
	public HashMap<String, Object> IncreaseReservation(long hotelId,long resId,long days) throws EntityNotFoundException, ParseException{
		Reservation res = GetReservation(resId);
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		Date df = res.getDateTo();
					
		if(res.getSubReservationList().size() == 0){
			long roomId = res.getRoom().getId();
			List<SubReservation> sub = GetReservationWithinDateInSpecificRoom(hotelId, df, days, roomId);
			boolean canbeMove = true;
			for(SubReservation s:sub)
				if(s.isAssign(this) || !CanBeChangeRoomWithSellRoom(s)) { canbeMove = false; break; }
			if(canbeMove){
				for(SubReservation s:sub)
					AutoMoveRoomWithSellRoom(s);
			
				res.setSpan(res.getSpan() + days);			
				String pbdString = EditPackageByDate(res.getPackageByDate(), res.getDate(), res.getDateTo());
				res.setPackageByDateString(pbdString);
				res = UpdateReservation(res);
		
				List<SubReservation> sublist = res.getSubReservationList();
				if(sublist.size() ==0){
					SubReservation aa = new SubReservation();
					aa.CloneReservation(res);
					sublist.add(aa);
				}
				List<Charge> chargelist = res.getChargeList();
				Date mindate = chargelist.get(0).getChargeDate();
				Date maxdate = chargelist.get(0).getChargeDate();
				for(int i=0;i<chargelist.size();i++){
					if(chargelist.get(i).getChargeDate().before(mindate)){
						mindate = chargelist.get(i).getChargeDate();
					}
					if(chargelist.get(i).getChargeDate().after(maxdate)){
						maxdate = chargelist.get(i).getChargeDate();
					}
				}
				
				List<Charge> chargeList = new ChargeLogic(req,resp).CalCharge(hotelId, sublist, 
						res.getPackageByDate(),mindate,maxdate);
				map.put("SplitTable", sublist);
				map.put("PackageTable", res.getPackageByDate());
				map.put("ChargeList", chargeList);
			}
		}else{
			//have subreservation
			List<SubReservation> subres = res.getSubReservationList();
			SubReservationLogic srLogic = new SubReservationLogic(req,resp);

			SubReservation lastsub = srLogic.GetLastSubRes(subres);
			
			List<SubReservation> sub = GetReservationWithinDateInSpecificRoom(hotelId, df, days, lastsub.getRoom().getId());
			boolean canbeMove = true;
			for(SubReservation s:sub)
				if(s.isAssign(this) || !CanBeChangeRoomWithSellRoom(s)) { canbeMove = false; break; }
			if(canbeMove){
				for(SubReservation s:sub)
					AutoMoveRoomWithSellRoom(s);
				
				Date newFrom = res.getDate();
				Date newTo = Util.addDays(res.getDate(), res.getSpan()+days);
				subres = srLogic.EditSubResvListDate(subres,newFrom,newTo);
				
				@SuppressWarnings("unused")
				String subresstring = null;
				for(int d = 0;d<subres.size();d++){
					subresstring += subres.get(d).getId()+",";
				}
				
				res.setSpan(res.getSpan() + days);			
				String pbdString = EditPackageByDate(res.getPackageByDate(), res.getDate(), res.getDateTo());
				res.setPackageByDateString(pbdString);
				res = UpdateReservation(res);
				
				List<SubReservation> sublist = res.getSubReservationList();
				if(sublist.size() ==0){
					SubReservation aa = new SubReservation();
					aa.CloneReservation(res);
					sublist.add(aa);
				}
				List<Charge> chargelist = res.getChargeList();
				Date mindate = chargelist.get(0).getChargeDate();
				Date maxdate = chargelist.get(0).getChargeDate();
				for(int i=0;i<chargelist.size();i++){
					if(chargelist.get(i).getChargeDate().before(mindate)){
						mindate = chargelist.get(i).getChargeDate();
					}
					if(chargelist.get(i).getChargeDate().after(maxdate)){
						maxdate = chargelist.get(i).getChargeDate();
					}
				}
				
				List<Charge> chargeList = new ChargeLogic(req,resp).CalCharge(hotelId, subres, 
						res.getPackageByDate(),mindate,maxdate);
				map.put("SplitTable", subres);
				map.put("PackageTable", res.getPackageByDate());
				map.put("ChargeList", chargeList);
			}
		}
		return map;
	}
	
	public HashMap<String, Object> EditDetailResvCheckInCheckOut(long hotelId,long resId,Date date,long span) throws EntityNotFoundException, ParseException{
		Reservation res = GetReservation(resId);

		if(res.getSubReservationList().size() == 0){
			//no have subreservation
			//edit in reservation
			res = EditDetailReservation(hotelId, resId, date, span);
			
			// edit package by date
			String pbdString = EditPackageByDate(res.getPackageByDate(), date, Util.addDays(date,span));
			res.setPackageByDateString(pbdString);
			res = UpdateReservation(res);
			
			List<SubReservation> sublist = res.getSubReservationList();
			if(sublist.size() ==0){
				SubReservation aa = new SubReservation();
				aa.CloneReservation(res);
				sublist.add(aa);
			}
			List<Charge> chargelist = res.getChargeList();
			Date mindate = chargelist.get(0).getChargeDate();
			Date maxdate = chargelist.get(0).getChargeDate();
			for(int i=0;i<chargelist.size();i++){
				if(chargelist.get(i).getChargeDate().before(mindate)){
					mindate = chargelist.get(i).getChargeDate();
				}
				if(chargelist.get(i).getChargeDate().after(maxdate)){
					maxdate = chargelist.get(i).getChargeDate();
				}
			}
			
			List<Charge> chargeList = new ChargeLogic(req,resp).CalCharge(hotelId, sublist, 
					res.getPackageByDate(),mindate,maxdate);
			
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("Charge", chargeList);
			map.put("date", res.getDate());
			map.put("span", res.getSpan());
			
			return map;
		}else{
			//have subreservation
			List<SubReservation> subres = res.getSubReservationList();
			SubReservationLogic srLogic = new SubReservationLogic(req,resp);

			Date newFrom = date;
			Date newTo = Util.addDays(date, span);
			subres = srLogic.EditSubResvListDate(subres,newFrom,newTo);
			
			String subresstring = "";
			for(int d = 0;d<subres.size();d++){
				subresstring += subres.get(d).getId()+",";
			}
			res = EditSubResString(resId, subresstring.substring(0, subresstring.length() - 1));
			res = EditDetailReservation(hotelId, resId, date, span);
			
			// edit package by date
			String pbdString = EditPackageByDate(res.getPackageByDate(), date, Util.addDays(date,span));
			res.setPackageByDateString(pbdString);
			res = UpdateReservation(res);
			
			List<SubReservation> sublist = res.getSubReservationList();
			if(sublist.size() ==0){
				SubReservation aa = new SubReservation();
				aa.CloneReservation(res);
				sublist.add(aa);
			}
			List<Charge> chargelist = res.getChargeList();
			Date mindate = chargelist.get(0).getChargeDate();
			Date maxdate = chargelist.get(0).getChargeDate();
			for(int i=0;i<chargelist.size();i++){
				if(chargelist.get(i).getChargeDate().before(mindate)){
					mindate = chargelist.get(i).getChargeDate();
				}
				if(chargelist.get(i).getChargeDate().after(maxdate)){
					maxdate = chargelist.get(i).getChargeDate();
				}
			}
			
			List<Charge> chargeList = new ChargeLogic(req,resp).CalCharge(hotelId, subres, 
					res.getPackageByDate(),mindate,maxdate);

			double cost = 0;
			for(Charge c:chargeList)
				cost += c.getChargeAmount();
			
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("cost", cost);
			map.put("date", res.getDate());
			map.put("span", res.getSpan());
			
			return map;
		}
	}
	
	public ReservationDataFullWithTask FillReservationDataFullWithTask(Reservation res)
	{
		ReservationDataFullWithTask datafull = new ReservationDataFullWithTask();
		datafull.setId(res.getId());
		datafull.setAdult(res.getAdult());
		datafull.setChild(res.getChild());
		datafull.setGuestString(res.getGuestString());
		if(!res.getGuestString().equals("0")){
			if(res.getGuest().getSalutation() == null){
				datafull.setSalutation("");
			}else{
				datafull.setSalutation(res.getGuest().getSalutation().getTitle());
			}
			datafull.setGuestName(res.getGuest().getFirstName());
			datafull.setGuestLastName(res.getGuest().getLastName());
			datafull.setGuestTel(res.getGuest().getPhone());
		}
		datafull.setPaymentListString(res.getPaymentListString());
		datafull.setChargeListString(res.getChargeListString());
		datafull.setOtherChargeListString(res.getOtherChargeString());
		datafull.setReservationStatusName(res.getReservationStatus().getTitle());
		datafull.setReservationStatusString(res.getReservationStatusString());
		datafull.setDate(res.getDate());
		datafull.setSpan(res.getSpan());
		List<PackageByDate> pbd = res.getPackageByDate();
		datafull.setPricePackageId(pbd.get(0).getPackageString());
		String packageName = "";
		for(int x=0;x<pbd.size();x++){
			if(packageName == "") packageName = pbd.get(x).getPackages().getName();
			else if(!packageName.equals(pbd.get(x).getPackages().getName())) { packageName = "Multiple Package"; datafull.setPricePackageId(""); }
			//packageName += pbd.get(x).getPackages().getName()+",";
		}
		//packageName.substring(0, packageName.length()-1)
		datafull.setPriceRateName(packageName);
		datafull.setPriceRateString(res.getPackageByDateString());
		datafull.setTasks(res.getTaskList());
		
		if(res.getSubReservationList().size() ==0){
			datafull.setRoomName(res.getRoom().getRoomName());
			datafull.setRoomString(res.getRoomString());
			datafull.setRoomTypeName(res.getRoomType().getShortName());
			datafull.setRoomTypeString(res.getRoomTypeString());
		}else{
			String roomname = "";
			for(int k =0;k<res.getSubReservationList().size();k++){
				roomname += res.getSubReservationList().get(k).getRoom().getRoomName() + ",";
			}
			datafull.setRoomName(roomname.substring(0, roomname.length() - 1));
			datafull.setRoomString("MultipleRoom");
			datafull.setRoomTypeName("MultipleRoomType");
			datafull.setRoomTypeString("MultipleRoomType");
		}
		
		return datafull;
	}

	public List<Reservation> GetCheckinToday(long hotelId)
	{
		GenericLogic gLogic = new GenericLogic(req,resp);
		Date d = Util.GetOnlyDate(gLogic.ServerDateFromNightAudit(hotelId));
		return GetCheckinSpecificDate(hotelId,d);
	}
	public List<Reservation> GetCheckinSpecificDate(long hotelId,Date d){
		Query q = new Query(EntityName.Reservation);
		Filter filterhotelId = new FilterPredicate("hotelId",
				FilterOperator.EQUAL, hotelId);
		Filter filterDate = new FilterPredicate("date",
				FilterOperator.EQUAL, d);
		Filter filter = CompositeFilterOperator.and(filterhotelId,filterDate);
		q.setFilter(filter);
		List<Reservation> list1 = GetList(datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()));
		
		return list1;
	}
	
	public List<NightAuditReportResData> GetResCheckInToDay(long hotelId){
		List<Reservation> resCheckIn = GetCheckedinToday(hotelId);
		List<NightAuditReportResData> result = new ArrayList<NightAuditReportResData>();
		for(int i=0;i<resCheckIn.size();i++){
			NightAuditReportResData data = new NightAuditReportResData();
			data.setCheckInTime(resCheckIn.get(i).getDateCheckin());
			data.setCheckOutTime(Util.addDays(resCheckIn.get(i).getDateCheckin(), resCheckIn.get(i).getSpan()));
			double pay = 0;
			if(resCheckIn.get(i).getPaymentList() != null){
				for(int x=0;x<resCheckIn.get(i).getPaymentList().size();x++){
					pay += resCheckIn.get(i).getPaymentList().get(x).getAmount();
				}
			}
			data.setPay(pay);
			data.setResId(resCheckIn.get(i).getId());
			data.setRoomName(resCheckIn.get(i).getRoom().getRoomName());
			data.setRoomtypeName(resCheckIn.get(i).getRoomType().getShortName());
			if(resCheckIn.get(i).getAdditionalGuest() != null){
				data.setUserId(resCheckIn.get(i).getAdditionalGuest().get(0).getId());
				String userName = resCheckIn.get(i).getAdditionalGuest().get(0).getFirstName();
				if(!resCheckIn.get(i).getAdditionalGuest().get(0).getSalutationString().equals("0") &&
						resCheckIn.get(i).getAdditionalGuest().get(0).getSalutationString() != null	){
					userName = resCheckIn.get(i).getAdditionalGuest().get(0).getSalutation().getTitle()
							+userName;
				}
				if(resCheckIn.get(i).getAdditionalGuest().get(0).getLastName() != null){
					userName += " " + resCheckIn.get(i).getAdditionalGuest().get(0).getLastName();
				}
				data.setUserName(userName);
			}
			result.add(data);
		}
		return result;
	}
	public List<Reservation> GetCheckedinToday(long hotelId)
	{
		GenericLogic gLogic = new GenericLogic(req,resp);
		Date d = Util.GetOnlyDate(gLogic.ServerDateFromNightAudit(hotelId));
		String resStatus = String.valueOf(gLogic.GetReservationStatus(hotelId, 
				StatusTitle.ReservationStatus.CheckedInRooms).getId());
		return GetCheckedinSpecificDate(hotelId,d,resStatus);
	}
	public List<Reservation> GetCheckedinSpecificDate(long hotelId,Date d,String resStatus){
		Query q = new Query(EntityName.Reservation);
		Filter filterhotelId = new FilterPredicate("hotelId",
				FilterOperator.EQUAL, hotelId);
		Filter filterDate = new FilterPredicate("date",
				FilterOperator.EQUAL, d);
		Filter filterStatus = new FilterPredicate("ReservationStatus",
				FilterOperator.EQUAL, resStatus);
		Filter filter = CompositeFilterOperator.and(filterhotelId,filterDate,filterStatus);
		q.setFilter(filter);
		List<Reservation> list1 = GetList(datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()));
		
		return list1;
	}
	
	public List<Reservation> GetCheckoutToday(long hotelId)
	{
		GenericLogic gLogic = new GenericLogic(req,resp);
		Date d = Util.GetOnlyDate(gLogic.ServerDateFromNightAudit(hotelId));
		return GetCheckoutSpecificDate(hotelId,d);
	}
	public List<Reservation> GetCheckoutSpecificDate(long hotelId,Date d)
	{
		Query q = new Query(EntityName.Reservation);
		Filter filterhotelId = new FilterPredicate("hotelId",
				FilterOperator.EQUAL, hotelId);
		Filter filterDate = new FilterPredicate("dateTo",
				FilterOperator.EQUAL, d);
		Filter filter = CompositeFilterOperator.and(filterhotelId,filterDate);
		q.setFilter(filter);
		List<Reservation> list1 = GetList(datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()));
		
		return list1;
	}
	public List<Reservation> GetStayToday(long hotelId){
		GenericLogic gLogic = new GenericLogic(req,resp);
		Date d = Util.GetOnlyDate(gLogic.ServerDateFromNightAudit(hotelId));
		return GetStaySpecificDate(hotelId,d);
	}
	public List<Reservation> GetStaySpecificDate(long hotelId,Date d){
		Query q = new Query(EntityName.
				Reservation);
		Filter filterhotelId = new FilterPredicate("hotelId",
				FilterOperator.EQUAL, hotelId);
		Filter filterDate = new FilterPredicate("date",
				FilterOperator.LESS_THAN, d);
		Filter filter = CompositeFilterOperator.and(filterhotelId,filterDate);
		q.setFilter(filter);
		List<Reservation> list1 = GetList(datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()));
		List<Reservation> list2 = new ArrayList<Reservation>();
		for(Reservation r:list1)
			if(r.getDateTo().after(d))
				list2.add(r);
		return list2;
	}
			
	public List<Reservation> GetCancelToDay(long hotelId){
		GenericLogic gLogic = new GenericLogic(req,resp);
		String resStatus = String.valueOf(gLogic.GetReservationStatus(hotelId,StatusTitle.ReservationStatus.CancelReservation).getId());
		Date d = Util.GetOnlyDate(gLogic.ServerDateFromNightAudit(hotelId));
		Query q = new Query(EntityName.Reservation);
		Filter filterhotelId = new FilterPredicate("hotelId",
				FilterOperator.EQUAL, hotelId);
		Filter filterDate = new FilterPredicate("dateTo",
				FilterOperator.EQUAL, d);
		Filter filterResStatus = new FilterPredicate("ReservationStatus",
				FilterOperator.EQUAL, resStatus);
		Filter filter = CompositeFilterOperator.and(filterhotelId,filterDate,filterResStatus);
		q.setFilter(filter);
		List<Reservation> list1 = GetList(datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()));
		List<Reservation> list2 = new ArrayList<Reservation>();
		for(Reservation r:list1)
			if(r.getDateTo().after(d))
				list2.add(r);
		return list2;
	}

	
	public List<Reservation> GetDNRToday(long hotelId){
		GenericLogic gLogic = new GenericLogic(req,resp);
		Date d = Util.GetOnlyDate(gLogic.ServerDateFromNightAudit(hotelId));
		return GetDNRSpecificDate(hotelId,d);
	}
	
	public List<Reservation> GetDNRYesterday(long hotelId){
		GenericLogic gLogic = new GenericLogic(req,resp);
		Date d = Util.addDays(Util.GetOnlyDate(gLogic.ServerDateFromNightAudit(hotelId)), -1);
		return GetDNRSpecificDate(hotelId,d);
	}
	
	public List<Reservation> GetDNRSpecificDate(long hotelId,Date d){
		DNRLogic dnrLogic = new DNRLogic(req,resp);
		List<DNR> list = dnrLogic.GetExistDNR(hotelId, d);
		List<Reservation> result = new ArrayList<Reservation>();
		for(DNR dnr:list)
			if(!dnr.getDate().after(d))
				result.add(dnrLogic.DNRtoReservation(dnr));
		return result;
	}
	
	public HashMap<String,Object> MinReservationData(ReservationData resData){
		HashMap<String,Object> hash = new HashMap<String,Object>();
		//hash.put("a",resData.getAdult());
		//hash.put("c",resData.getChild());
		hash.put("d",resData.getDate());
		hash.put("gId",resData.getGroupId());
		hash.put("id", resData.getId());
		hash.put("A", resData.isAssign());
		hash.put("cf", resData.isChangeRoomFrom());
		hash.put("ct", resData.isChangeRoomTo());
		hash.put("nm", resData.getName());
		hash.put("o", resData.getOrder());
		hash.put("rlD", resData.getRealDate());
		hash.put("rlS", resData.getRealSpan());
		hash.put("rsSt", resData.getResStatus());
		hash.put("rmId", resData.getRoomNameId());
		//hash.put("rmTId", resData.getRoomTypeId());
		hash.put("sRm", resData.isSellRoom());
		hash.put("s", resData.getSpan());
		hash.put("subId", resData.getSubId());
		if(resData.getGroupName()!=null && resData.getGroupName()!="")
			hash.put("gNm", resData.getGroupName());
		return hash;
	}
	
	public List<Reservation> GetReservationByRoom(long hotelId, long roomId) {
		Query q = new Query(EntityName.Reservation);
		Filter filterhotelId = new FilterPredicate("hotelId",
				FilterOperator.EQUAL, hotelId);
		Filter filterroomId = new FilterPredicate("roomId",
				FilterOperator.EQUAL, String.valueOf(roomId));
		Filter filter = CompositeFilterOperator.and(filterhotelId, filterroomId);
		q.setFilter(filter);
		return GetList(datastore.prepare(q).asList(
				FetchOptions.Builder.withDefaults()));
	}
	
	public List<Reservation> GetReservationByRoomType(long hotelId, long roomtypeid) {
		Query q = new Query(EntityName.Reservation);
		Filter filterhotelId = new FilterPredicate("hotelId",
				FilterOperator.EQUAL, hotelId);
		Filter filterroomId = new FilterPredicate("roomType",
				FilterOperator.EQUAL, String.valueOf(roomtypeid));
		Filter filter = CompositeFilterOperator.and(filterhotelId, filterroomId);
		q.setFilter(filter);
		return GetList(datastore.prepare(q).asList(
				FetchOptions.Builder.withDefaults()));
	}
}
